@hupu-tech/shaper 0.2.12 → 0.2.14

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 (192) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +6 -0
  3. package/dist/auth/auth.d.ts +1 -0
  4. package/dist/cli.js +2 -2
  5. package/dist/cloud/client.d.ts +0 -1
  6. package/dist/cloud/service-build.d.ts +2 -4
  7. package/dist/index.js +1 -1
  8. package/dist/platform/api.d.ts +2 -0
  9. package/dist/project/create.d.ts +9 -3
  10. package/dist/project/delivery.d.ts +5 -5
  11. package/dist/runtime.d.ts +2 -1
  12. package/dist/runtime.js +1 -1
  13. package/dist/shared-UKIFY6QO.js +19 -0
  14. package/package.json +1 -1
  15. package/skills/business/SKILL.md +158 -0
  16. package/skills/business/activity/README.md +14 -0
  17. package/skills/business/activity/hupu-leaderboard-template/SKILL.md +52 -0
  18. package/skills/business/activity/hupu-leaderboard-template/example/README.md +20 -0
  19. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/.cloudignore +3 -0
  20. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/index.js +218 -0
  21. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/package.json +15 -0
  22. package/skills/business/activity/hupu-leaderboard-template/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  23. package/skills/business/activity/hupu-leaderboard-template/example/index.html +291 -0
  24. package/skills/business/activity/hupu-leaderboard-template/example/migrations/20260828210000_create_leaderboard.sql +54 -0
  25. package/skills/business/activity/hupu-lottery-draw/SKILL.md +50 -0
  26. package/skills/business/activity/hupu-lottery-draw/example/README.md +21 -0
  27. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/.cloudignore +3 -0
  28. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/index.js +142 -0
  29. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/package.json +9 -0
  30. package/skills/business/activity/hupu-lottery-draw/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  31. package/skills/business/activity/hupu-lottery-draw/example/index.html +178 -0
  32. package/skills/business/activity/hupu-lottery-draw/example/migrations/20260828220000_create_draw.sql +193 -0
  33. package/skills/business/activity/hupu-pk-voting/SKILL.md +54 -0
  34. package/skills/business/activity/hupu-pk-voting/example/README.md +44 -0
  35. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/.cloudignore +3 -0
  36. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/index.js +370 -0
  37. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/package.json +15 -0
  38. package/skills/business/activity/hupu-pk-voting/example/cloudfunctions/activity_api/scf_bootstrap +2 -0
  39. package/skills/business/activity/hupu-pk-voting/example/index.html +729 -0
  40. package/skills/business/activity/hupu-pk-voting/example/migrations/20260828220000_create_pk_vote.sql +168 -0
  41. package/skills/business/activity/hupu-request-activity-execute-vote-task/SKILL.md +77 -0
  42. package/skills/business/activity/hupu-request-activity-get-vote-detail/SKILL.md +84 -0
  43. package/skills/business/activity/hupu-request-activity-get-vote-task-list/SKILL.md +86 -0
  44. package/skills/business/activity/hupu-request-activity-list-by-biz-keys/SKILL.md +153 -0
  45. package/skills/business/activity/hupu-request-activity-report-vote-task/SKILL.md +58 -0
  46. package/skills/business/activity/hupu-request-activity-submit-vote/SKILL.md +58 -0
  47. package/skills/business/activity/hupu-vote-task/SKILL.md +47 -0
  48. package/skills/business/community/README.md +13 -0
  49. package/skills/business/community/hupu-request-bbs-detail/SKILL.md +197 -0
  50. package/skills/business/community/hupu-request-bbs-get-tag-thread-list/SKILL.md +257 -0
  51. package/skills/business/community/hupu-request-bbs-get-topic-threads/SKILL.md +159 -0
  52. package/skills/business/community/hupu-request-bbs-gets-thread-post-list/SKILL.md +124 -0
  53. package/skills/business/community/hupu-request-bbs-open-post-editor/SKILL.md +75 -0
  54. package/skills/business/community/hupu-request-bbs-reply-post/SKILL.md +59 -0
  55. package/skills/business/community/hupu-score-add-score/SKILL.md +57 -0
  56. package/skills/business/community/hupu-score-get-item-detail/SKILL.md +173 -0
  57. package/skills/business/community/hupu-score-get-score/SKILL.md +263 -0
  58. package/skills/business/quality/README.md +7 -0
  59. package/skills/business/quality/hupu-security-check-audit/SKILL.md +39 -0
  60. package/skills/business/quality/hupu-wasm-compression/SKILL.md +69 -0
  61. package/skills/business/quality/hupu-wasm-compression/agents/openai.yaml +4 -0
  62. package/skills/business/quality/hupu-wasm-compression/tool/checks.mjs +90 -0
  63. package/skills/business/quality/hupu-wasm-compression/tool/compress-worker.mjs +40 -0
  64. package/skills/business/quality/hupu-wasm-compression/tool/public/app.js +84 -0
  65. package/skills/business/quality/hupu-wasm-compression/tool/public/index.html +80 -0
  66. package/skills/business/quality/hupu-wasm-compression/tool/public/style.css +3 -0
  67. package/skills/business/quality/hupu-wasm-compression/tool/server.mjs +126 -0
  68. package/skills/business/quality/hupu-web-security-audit/SKILL.md +45 -0
  69. package/skills/business/quality/hupu-web-security-audit/agents/openai.yaml +4 -0
  70. package/skills/business/rewards/README.md +13 -0
  71. package/skills/business/rewards/hupu-vacoin/SKILL.md +70 -0
  72. package/skills/business/rewards/hupu-vacoin-consume-coins/SKILL.md +47 -0
  73. package/skills/business/rewards/hupu-vacoin-get-coin-overview/SKILL.md +52 -0
  74. package/skills/business/rewards/hupu-vacoin-get-session-coins/SKILL.md +44 -0
  75. package/skills/business/rewards/hupu-vacoin-reset-session-id/SKILL.md +39 -0
  76. package/skills/business/rewards/hupu-vatask/SKILL.md +63 -0
  77. package/skills/business/rewards/hupu-vatask-complete-reward-video/SKILL.md +43 -0
  78. package/skills/business/rewards/hupu-vatask-consume-activity-chance/SKILL.md +48 -0
  79. package/skills/business/rewards/hupu-vatask-get-activity-task-state/SKILL.md +49 -0
  80. package/skills/business/runtime/README.md +13 -0
  81. package/skills/business/runtime/hupu-add-to-desktop/SKILL.md +51 -0
  82. package/skills/business/runtime/hupu-close-webview/SKILL.md +48 -0
  83. package/skills/business/runtime/hupu-cloud-auth/SKILL.md +43 -0
  84. package/skills/business/runtime/hupu-cloud-request/SKILL.md +56 -0
  85. package/skills/business/runtime/hupu-fullscreen-safe-top/SKILL.md +33 -0
  86. package/skills/business/runtime/hupu-navigate-to/SKILL.md +45 -0
  87. package/skills/business/runtime/hupu-request/SKILL.md +67 -0
  88. package/skills/business/runtime/hupu-seer-chat/SKILL.md +183 -0
  89. package/skills/business/runtime/hupu-track-report/SKILL.md +71 -0
  90. package/skills/business/sharing/README.md +7 -0
  91. package/skills/business/sharing/hupu-oss-upload-file/SKILL.md +40 -0
  92. package/skills/business/sharing/hupu-result-poster-posting/SKILL.md +37 -0
  93. package/skills/business/sharing/hupu-result-poster-posting/example/README.md +14 -0
  94. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/.cloudignore +3 -0
  95. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/index.js +187 -0
  96. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/package.json +15 -0
  97. package/skills/business/sharing/hupu-result-poster-posting/example/cloudfunctions/activity_api/scf_bootstrap +3 -0
  98. package/skills/business/sharing/hupu-result-poster-posting/example/index.html +256 -0
  99. package/skills/business/sharing/hupu-result-poster-posting/example/migrations/20260828213000_create_result_poster_results.sql +60 -0
  100. package/skills/business/sharing/hupu-result-poster-posting/references/api-contract.md +46 -0
  101. package/skills/business/sharing/hupu-social-share/SKILL.md +27 -0
  102. package/skills/business/sports/README.md +27 -0
  103. package/skills/business/sports/hupu-request-basketball-player-info/SKILL.md +131 -0
  104. package/skills/business/sports/hupu-request-basketball-single-match/SKILL.md +158 -0
  105. package/skills/business/sports/hupu-request-basketball-team-info/SKILL.md +96 -0
  106. package/skills/business/sports/hupu-request-basketball-team-player-list/SKILL.md +108 -0
  107. package/skills/business/sports/hupu-request-basketball-team-salary-info/SKILL.md +85 -0
  108. package/skills/business/sports/hupu-request-football-coach-info/SKILL.md +76 -0
  109. package/skills/business/sports/hupu-request-football-live-room-news-list/SKILL.md +85 -0
  110. package/skills/business/sports/hupu-request-football-match-info/SKILL.md +126 -0
  111. package/skills/business/sports/hupu-request-football-player-info/SKILL.md +82 -0
  112. package/skills/business/sports/hupu-request-football-team-info/SKILL.md +83 -0
  113. package/skills/business/sports/hupu-request-football-team-player-season-stats/SKILL.md +73 -0
  114. package/skills/business/sports/hupu-request-football-team-season-year/SKILL.md +68 -0
  115. package/skills/business/sports/hupu-request-kog-playbyplay/SKILL.md +77 -0
  116. package/skills/business/sports/hupu-request-live-tab-info-list/SKILL.md +85 -0
  117. package/skills/business/sports/hupu-request-live-tab-list/SKILL.md +66 -0
  118. package/skills/business/sports/hupu-request-lol-playbyplay/SKILL.md +77 -0
  119. package/skills/business/sports/hupu-request-match-get-tab-detail-schedule-list/SKILL.md +113 -0
  120. package/skills/business/sports/hupu-request-match-query-all-diagram-info-by-id/SKILL.md +79 -0
  121. package/skills/business/sports/hupu-request-match-query-match-stats-by-match-info/SKILL.md +85 -0
  122. package/skills/business/sports/hupu-request-news-news-common-list/SKILL.md +90 -0
  123. package/skills/business/sports/hupu-request-news-player-news-list/SKILL.md +79 -0
  124. package/skills/business/sports/hupu-request-news-subject-news/SKILL.md +89 -0
  125. package/skills/business/sports/hupu-request-news-team-news-list/SKILL.md +76 -0
  126. package/skills/business/storage/README.md +9 -0
  127. package/skills/business/storage/hupu-cloud-save/SKILL.md +129 -0
  128. package/skills/business/storage/hupu-cloud-save/references/legacy-migration.md +111 -0
  129. package/skills/business/storage/hupu-cloud-save-load/SKILL.md +41 -0
  130. package/skills/business/storage/hupu-cloud-save-save/SKILL.md +45 -0
  131. package/skills/business/storage/hupu-storage-get-value/SKILL.md +26 -0
  132. package/skills/business/storage/hupu-storage-set-value/SKILL.md +42 -0
  133. package/skills/business/user/README.md +6 -0
  134. package/skills/business/user/hupu-auth-get-user-info/SKILL.md +47 -0
  135. package/skills/business/user/hupu-game-auth/SKILL.md +46 -0
  136. package/skills/core/hupu-business/SKILL.md +1 -1
  137. package/skills/core/hupu-business/references/runtime.md +17 -11
  138. package/skills/core/shaper-backend/SKILL.md +1 -1
  139. package/skills/core/shaper-backend/references/database.md +2 -2
  140. package/skills/core/shaper-backend/references/legacy.md +1 -1
  141. package/skills/core/shaper-backend/references/node-server.md +29 -20
  142. package/skills/core/shaper-development/SKILL.md +6 -1
  143. package/skills/core/shaper-development/references/materials.md +14 -0
  144. package/skills/core/shaper-development/references/project-setup.md +1 -1
  145. package/skills/core/shaper-game-development/SKILL.md +16 -9
  146. package/skills/core/shaper-game-development/references/implementation.md +13 -0
  147. package/skills/core/shaper-game-development/references/iteration.md +11 -0
  148. package/skills/core/shaper-game-development/references/playable-loop.md +12 -0
  149. package/skills/core/shaper-game-development/references/playtest.md +18 -0
  150. package/skills/core/shaper-game-development/references/sources.md +6 -0
  151. package/skills/core/shaper-release/SKILL.md +1 -1
  152. package/templates/cloud-service/README.md +4 -30
  153. package/templates/cloud-service/cloud.json +5 -8
  154. package/templates/cloud-service/package-lock.json +922 -15
  155. package/templates/cloud-service/release.json +4 -4
  156. package/templates/cloud-service/server.cjs +37 -0
  157. package/templates/leaderboard/README.md +3 -0
  158. package/templates/leaderboard/cloud/database/migrations/202611130001_leaderboard.sql +6 -0
  159. package/templates/leaderboard/cloud/functions/api/cloud.json +10 -0
  160. package/templates/leaderboard/cloud/functions/api/leaderboard.cjs +49 -0
  161. package/templates/leaderboard/cloud/functions/api/package-lock.json +1093 -0
  162. package/templates/leaderboard/cloud/functions/api/package.json +19 -0
  163. package/templates/leaderboard/cloud/functions/api/server.cjs +25 -0
  164. package/templates/leaderboard/cloud/gateway/routes.json +15 -0
  165. package/templates/leaderboard/docs/design.md +1 -0
  166. package/templates/leaderboard/docs/integration.md +12 -0
  167. package/templates/leaderboard/docs/product.md +1 -0
  168. package/templates/leaderboard/docs/validation.md +1 -0
  169. package/templates/leaderboard/index.html +12 -0
  170. package/templates/leaderboard/package-lock.json +828 -0
  171. package/templates/leaderboard/package.json +17 -0
  172. package/templates/leaderboard/public/.gitkeep +1 -0
  173. package/templates/leaderboard/shaper.config.json +7 -0
  174. package/templates/leaderboard/src/main.js +67 -0
  175. package/templates/leaderboard/src/style.css +69 -0
  176. package/templates/leaderboard/test/leaderboard.test.cjs +93 -0
  177. package/templates/offline-game/README.md +3 -0
  178. package/templates/offline-game/docs/design.md +1 -0
  179. package/templates/offline-game/docs/integration.md +10 -0
  180. package/templates/offline-game/docs/product.md +1 -0
  181. package/templates/offline-game/docs/validation.md +1 -0
  182. package/templates/offline-game/index.html +12 -0
  183. package/templates/offline-game/package-lock.json +828 -0
  184. package/templates/offline-game/package.json +16 -0
  185. package/templates/offline-game/public/.gitkeep +1 -0
  186. package/templates/offline-game/shaper.config.json +7 -0
  187. package/templates/offline-game/src/game.js +42 -0
  188. package/templates/offline-game/src/main.js +60 -0
  189. package/templates/offline-game/src/style.css +69 -0
  190. package/templates/offline-game/test/game.test.js +25 -0
  191. package/dist/shared-APGA5MU5.js +0 -19
  192. package/templates/cloud-service/handlers.cjs +0 -46
@@ -0,0 +1,90 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { once } from 'node:events';
4
+ import * as z from 'node:zlib';
5
+ import { createApp, negotiate } from './server.mjs';
6
+
7
+ const decoders = { br: z.brotliDecompressSync, gzip: z.gunzipSync, zstd: z.zstdDecompressSync };
8
+
9
+ test('Accept-Encoding honors quality, exclusions, wildcard and identity', () => {
10
+ const all = ['br', 'gzip', 'zstd', 'identity'];
11
+ assert.equal(negotiate('br;q=0, gzip;q=1, zstd;q=.5', all), 'gzip');
12
+ assert.equal(negotiate('br, gzip', all), 'br');
13
+ assert.equal(negotiate('*;q=0', all), undefined);
14
+ assert.equal(negotiate('', all), 'identity');
15
+ assert.equal(negotiate('gzip;q=.5', all), 'identity');
16
+ assert.equal(negotiate('zstd', ['gzip']), undefined);
17
+ });
18
+
19
+ test('uploaded wasm, round trip, encoded delivery and errors', async t => {
20
+ const server = createApp(); server.listen(0, '127.0.0.1'); await once(server, 'listening');
21
+ t.after(() => new Promise(resolve => server.close(resolve)));
22
+ const base = `http://127.0.0.1:${server.address().port}`;
23
+ const get = path => fetch(base + path);
24
+ const original = Buffer.from('0061736d010000000105016000017f030201000707010361646400000a06010400412a0b', 'hex');
25
+ assert.equal(WebAssembly.validate(original), true);
26
+ const service = await (await get('/api/status')).json();
27
+ assert.equal(service.maxBytes, null);
28
+ assert.equal((await get('/api/samples')).status, 404);
29
+ const bad = await fetch(base + '/api/jobs', { method: 'POST', body: 'not wasm' });
30
+ assert.equal(bad.status, 400);
31
+ const crossSite = await fetch(base + '/api/jobs', { method: 'POST', headers: { Origin: 'https://example.org' }, body: original });
32
+ assert.equal(crossSite.status, 403);
33
+ const created = await fetch(base + '/api/jobs?name=test.wasm&preset=fast', { method: 'POST', headers: { 'Content-Type': 'application/wasm' }, body: original });
34
+ assert.equal(created.status, 202);
35
+ let job = await created.json();
36
+ for (let tries = 0; tries < 100 && job.status === 'running'; tries++) {
37
+ await new Promise(resolve => setTimeout(resolve, 50));
38
+ job = await (await get(`/api/jobs/${job.id}`)).json();
39
+ }
40
+ assert.equal(job.status, 'done', job.error); assert.equal(job.results.length, 3);
41
+ for (const result of job.results) {
42
+ assert.equal(result.verified, true);
43
+ const download = await get(result.download);
44
+ assert.equal(download.headers.get('content-encoding'), null);
45
+ assert.match(download.headers.get('content-disposition'), /attachment/);
46
+ const compressed = Buffer.from(await download.arrayBuffer());
47
+ assert.equal(compressed.length, result.size);
48
+ assert.deepEqual(decoders[result.encoding](compressed), original);
49
+ }
50
+ const delivered = await fetch(`${base}/api/jobs/${job.id}/module/auto`, { headers: { 'Accept-Encoding': 'br;q=0,gzip;q=1' } });
51
+ assert.equal(delivered.headers.get('content-type'), 'application/wasm');
52
+ assert.equal(delivered.headers.get('content-encoding'), 'gzip');
53
+ assert.equal(delivered.headers.get('vary'), 'Accept-Encoding');
54
+ assert.deepEqual(Buffer.from(await delivered.arrayBuffer()), original);
55
+ const stream = await fetch(`${base}/api/jobs/${job.id}/module/br`, { headers: { 'Accept-Encoding': 'br' } });
56
+ const module = await WebAssembly.compileStreaming(stream);
57
+ assert.ok(WebAssembly.Module.exports(module).length > 0);
58
+ assert.equal((await fetch(`${base}/api/jobs/${job.id}/module/zstd`, { headers: { 'Accept-Encoding': 'gzip' } })).status, 406);
59
+ const upload = await fetch(base + '/api/jobs?name=uploaded.wasm&algorithms=gzip', { method: 'POST', headers: { 'Content-Type': 'application/wasm' }, body: original });
60
+ assert.equal(upload.status, 202); let uploaded = await upload.json();
61
+ for (let tries = 0; tries < 100 && uploaded.status === 'running'; tries++) {
62
+ await new Promise(resolve => setTimeout(resolve, 50));
63
+ uploaded = await (await get(`/api/jobs/${uploaded.id}`)).json();
64
+ }
65
+ assert.equal(uploaded.status, 'done'); assert.equal(uploaded.name, 'uploaded.wasm');
66
+ assert.equal(uploaded.results.length, 1);
67
+ assert.equal((await get('/server.mjs')).status, 404);
68
+
69
+ // A custom section keeps the large fixture valid without a large executable body.
70
+ const payloadLength = 33 * 1024 * 1024;
71
+ const leb = [];
72
+ for (let remaining = payloadLength; ; remaining = Math.floor(remaining / 128)) {
73
+ const next = remaining % 128;
74
+ leb.push(next | (remaining >= 128 ? 128 : 0));
75
+ if (remaining < 128) break;
76
+ }
77
+ const large = Buffer.concat([Buffer.from('0061736d01000000', 'hex'), Buffer.from([0, ...leb]), Buffer.alloc(payloadLength)]);
78
+ assert.equal(WebAssembly.validate(large), true);
79
+ const largeResponse = await fetch(base + '/api/jobs?name=large.wasm&algorithms=gzip', { method: 'POST', body: large });
80
+ assert.equal(largeResponse.status, 202);
81
+ let largeJob = await largeResponse.json();
82
+ for (let tries = 0; tries < 200 && largeJob.status === 'running'; tries++) {
83
+ await new Promise(resolve => setTimeout(resolve, 50));
84
+ largeJob = await (await get(`/api/jobs/${largeJob.id}`)).json();
85
+ }
86
+ assert.equal(largeJob.status, 'done', largeJob.error);
87
+ assert.equal(largeJob.size, large.length);
88
+ const largeDownload = await get(largeJob.results[0].download);
89
+ assert.deepEqual(z.gunzipSync(Buffer.from(await largeDownload.arrayBuffer())), large);
90
+ });
@@ -0,0 +1,40 @@
1
+ import { parentPort, workerData } from 'node:worker_threads';
2
+ import { createHash } from 'node:crypto';
3
+ import * as z from 'node:zlib';
4
+
5
+ const input = Buffer.from(workerData.bytes);
6
+ const hash = data => createHash('sha256').update(data).digest('hex');
7
+ const digest = hash(input);
8
+ const level = workerData.preset === 'archive'
9
+ ? { br: 11, gzip: 9, zstd: 19 }
10
+ : { br: 5, gzip: 6, zstd: 3 };
11
+ const codecs = {
12
+ br: [data => z.brotliCompressSync(data, { params: {
13
+ [z.constants.BROTLI_PARAM_QUALITY]: level.br,
14
+ [z.constants.BROTLI_PARAM_SIZE_HINT]: input.length,
15
+ } }), z.brotliDecompressSync],
16
+ gzip: [data => z.gzipSync(data, { level: level.gzip }), z.gunzipSync],
17
+ zstd: [data => z.zstdCompressSync(data, { params: {
18
+ [z.constants.ZSTD_c_compressionLevel]: level.zstd,
19
+ [z.constants.ZSTD_c_windowLog]: 23,
20
+ } }), z.zstdDecompressSync],
21
+ };
22
+
23
+ try {
24
+ for (const encoding of workerData.algorithms) {
25
+ parentPort.postMessage({ type: 'progress', encoding });
26
+ const [compress, decompress] = codecs[encoding];
27
+ const started = performance.now();
28
+ const bytes = compress(input);
29
+ const compressionMs = performance.now() - started;
30
+ const decodeStart = performance.now();
31
+ const decoded = decompress(bytes);
32
+ const decompressionMs = performance.now() - decodeStart;
33
+ if (!decoded.equals(input) || hash(decoded) !== digest) throw new Error('压缩回解校验失败');
34
+ parentPort.postMessage({ type: 'result', encoding, bytes, level: level[encoding],
35
+ compressionMs, decompressionMs, verified: true });
36
+ }
37
+ parentPort.postMessage({ type: 'done', sha256: digest });
38
+ } catch (error) {
39
+ parentPort.postMessage({ type: 'failure', error: error.message });
40
+ }
@@ -0,0 +1,84 @@
1
+ const $ = id => document.getElementById(id);
2
+ const names = { br: 'Brotli', gzip: 'gzip', zstd: 'Zstd', identity: '原始' };
3
+ let file, job, busy = false;
4
+ const size = n => n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KiB` : `${(n / 1024 / 1024).toFixed(3)} MiB`;
5
+ const ms = n => `${n.toFixed(1)} ms`;
6
+ function status(message, error = false) { $('status').textContent = message; $('status').classList.toggle('error', error); }
7
+ function lock(locked) {
8
+ busy = locked;
9
+ for (const el of document.querySelectorAll('aside button, aside select, aside input')) el.disabled = locked;
10
+ $('compress').disabled = locked || !file;
11
+ $('compress').querySelector('span').textContent = locked ? '正在压缩…' : '开始压缩对比';
12
+ }
13
+ function chooseFile(selected) {
14
+ if (!selected) return;
15
+ if (!selected.name.toLowerCase().endsWith('.wasm')) { status('请选择 .wasm 文件。', true); return; }
16
+ file = selected; $('file-info').textContent = `${file.name} · ${size(file.size)}`; lock(false); status('文件已就绪。');
17
+ }
18
+ $('file-input').onchange = e => chooseFile(e.target.files[0]);
19
+ for (const event of ['dragenter', 'dragover']) $('dropzone').addEventListener(event, e => { e.preventDefault(); if (!busy) $('dropzone').classList.add('drag'); });
20
+ for (const event of ['dragleave', 'drop']) $('dropzone').addEventListener(event, e => { e.preventDefault(); $('dropzone').classList.remove('drag'); });
21
+ $('dropzone').addEventListener('drop', e => { if (!busy) chooseFile(e.dataTransfer.files[0]); });
22
+ async function request(url, options) {
23
+ const response = await fetch(url, options);
24
+ const data = await response.json();
25
+ if (!response.ok) throw new Error(data.error || '请求失败');
26
+ return data;
27
+ }
28
+ function cell(row, value, className) { const td = document.createElement('td'); td.textContent = value; if (className) td.className = className; row.append(td); return td; }
29
+ function render(data) {
30
+ $('empty').hidden = true; $('results').hidden = false;
31
+ $('result-name').textContent = data.name; $('original-size').textContent = `原始体积 ${size(data.size)} · ${data.size.toLocaleString()} bytes`;
32
+ $('result-state').textContent = data.status === 'done' ? '校验通过' : data.status === 'failed' ? '任务失败' : '压缩中';
33
+ $('result-state').classList.toggle('done', data.status === 'done');
34
+ $('chart').replaceChildren(); $('result-rows').replaceChildren();
35
+ for (const item of [{ encoding: 'identity', size: data.size }, ...data.results]) {
36
+ const row = document.createElement('div'); row.className = 'bar-row';
37
+ const label = document.createElement('span'); label.textContent = names[item.encoding];
38
+ const track = document.createElement('div'); track.className = 'bar-track';
39
+ const bar = document.createElement('div'); bar.className = `bar ${item.encoding}`; bar.style.transform = `scaleX(${Math.min(1, item.size / data.size)})`; track.append(bar);
40
+ const value = document.createElement('span'); value.className = 'bar-value'; value.textContent = size(item.size);
41
+ row.append(label, track, value); $('chart').append(row);
42
+ }
43
+ const best = Math.min(...data.results.map(r => r.size));
44
+ for (const r of data.results) {
45
+ const row = document.createElement('tr');
46
+ const first = cell(row, `${names[r.encoding]} · ${r.level}`);
47
+ if (r.size === best && data.status === 'done') { const tag = document.createElement('small'); tag.textContent = '最小'; first.append(tag); }
48
+ cell(row, size(r.size)); cell(row, `${(r.saving * 100).toFixed(1)}%`, 'saving'); cell(row, ms(r.compressionMs)); cell(row, ms(r.decompressionMs));
49
+ const last = cell(row, ''); const a = document.createElement('a'); a.href = r.download; a.textContent = `下载 .${{ br: 'br', gzip: 'gz', zstd: 'zst' }[r.encoding]}`; a.setAttribute('download', ''); last.append(a);
50
+ $('result-rows').append(row);
51
+ }
52
+ $('sha').textContent = data.sha256;
53
+ $('verification').textContent = data.results.length ? `${data.results.length} 个结果已回解,原始字节与 SHA-256 一致。` : '正在生成并校验压缩结果…';
54
+ $('export').disabled = data.status !== 'done';
55
+ }
56
+ $('compress').onclick = async () => {
57
+ const algorithms = [...document.querySelectorAll('input[name=codec]:checked')].map(el => el.value);
58
+ if (!algorithms.length) { status('至少选择一种压缩算法。', true); return; }
59
+ lock(true); $('export').disabled = true;
60
+ status('正在将文件发送到本机…');
61
+ const params = new URLSearchParams({ preset: $('preset').value, algorithms: algorithms.join(','), name: file.name });
62
+ const options = { method: 'POST', body: file, headers: { 'Content-Type': 'application/wasm' } };
63
+ try {
64
+ job = await request(`/api/jobs?${params}`, options); render(job);
65
+ while (job.status === 'running') {
66
+ status(`正在压缩 ${names[job.current] || '模块'},请稍候…`);
67
+ await new Promise(resolve => setTimeout(resolve, 500));
68
+ job = await request(`/api/jobs/${job.id}`); render(job);
69
+ }
70
+ if (job.status === 'failed') throw new Error(job.error);
71
+ status('压缩完成,可以下载结果或导出 JSON。');
72
+ } catch (error) { status(error.message, true); }
73
+ finally { lock(false); }
74
+ };
75
+ $('export').onclick = () => {
76
+ if (!job) return;
77
+ const url = URL.createObjectURL(new Blob([JSON.stringify({ ...job, measuredAt: new Date().toISOString(), timing: 'Single-run Node wall-clock measurements; excludes upload and verification.' }, null, 2)], { type: 'application/json' }));
78
+ const a = document.createElement('a'); a.href = url; a.download = `${job.name}.compression.json`; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000);
79
+ };
80
+ try {
81
+ const data = await request('/api/status');
82
+ $('runtime').textContent = `${data.node} · 服务已连接`;
83
+ lock(false); status('选择或拖入 .wasm 文件后即可开始。');
84
+ } catch (error) { $('runtime').textContent = '服务连接失败'; status(error.message, true); }
@@ -0,0 +1,80 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <title>WASM 压缩实验室</title><link rel="stylesheet" href="/style.css"><script src="/app.js" type="module"></script>
6
+ </head>
7
+ <body>
8
+ <!-- THESIS: A file-to-evidence workbench for compressing WASM files.
9
+ OWN-WORLD: Inherit wasm-lab's cool light surfaces, indigo actions, ruled measurement rows, system UI typography.
10
+ STORY: Choose a real binary, compare lossless encodings, download and test native delivery.
11
+ FIRST VIEWPORT: Source rail on left, wide measured results on right; action anchored under compression settings.
12
+ FORM: Candidate 3, source-and-evidence split workbench; alternatives considered: wizard, single-column form, batch queue, comparison-first sheet. Seed edbcc136.
13
+ FINISH: unreviewed and undocumented is unfinished; this build ends with the finish review, the verdict, and DESIGN.md -->
14
+ <header class="masthead"><a class="brand" href="/" aria-label="WASM 压缩实验室首页"><svg viewBox="0 0 32 32" aria-hidden="true"><path d="M5 9h22M5 16h16M5 23h10M23 20v8m-4-4 4 4 4-4"/></svg>WASM <span>压缩实验室</span></a><span class="runtime" id="runtime">连接 Node 服务…</span></header>
15
+ <main>
16
+ <div class="intro"><div><h1>把 WASM 文件压得更小。</h1><p>上传现成文件,用 Node 实测压缩率,下载压缩结果用于你的项目。</p></div><span class="local-note">本机处理 · 无需源码</span></div>
17
+ <div class="workspace">
18
+ <aside class="source-panel">
19
+ <h2>选择 WASM 文件</h2>
20
+ <div id="upload-source"><label class="dropzone" id="dropzone" for="file-input"><svg viewBox="0 0 32 32" aria-hidden="true"><path d="M16 22V5m-6 6 6-6 6 6M5 20v7h22v-7"/></svg><strong>选择或拖入 .wasm 文件</strong><span>不设文件大小上限</span><input id="file-input" type="file" accept=".wasm,application/wasm"></label><p id="file-info" class="help">文件只发送到本机 Node 服务。</p></div>
21
+ <fieldset><legend>压缩算法</legend><label class="check"><input type="checkbox" name="codec" value="br" checked><span>Brotli <small>静态资源优先</small></span></label><label class="check"><input type="checkbox" name="codec" value="gzip" checked><span>gzip <small>兼容回退</small></span></label><label class="check"><input type="checkbox" name="codec" value="zstd" checked><span>Zstandard <small>速度与体积兼顾</small></span></label></fieldset>
22
+ <label for="preset">压缩档位</label><select id="preset"><option value="fast">快速对比 · br 5 / gzip 6 / zstd 3</option><option value="archive">最小体积 · br 11 / gzip 9 / zstd 19</option></select><p class="help">最小体积档更耗时,适合构建时预压缩。</p>
23
+ <button id="compress" class="primary" disabled><span>开始压缩对比</span><svg viewBox="0 0 20 20" aria-hidden="true"><path d="M3 10h14m-5-5 5 5-5 5"/></svg></button>
24
+ <p id="status" class="status" role="status" aria-live="polite">选择或拖入 .wasm 文件后即可开始。</p>
25
+ <p class="retention">结果保留 30 分钟,最多 6 个任务。重启服务可清空。</p>
26
+ </aside>
27
+ <div class="evidence">
28
+ <section aria-labelledby="results-heading">
29
+ <div class="section-heading"><h2 id="results-heading">压缩结果</h2><span id="result-state" class="tag">等待运行</span></div>
30
+ <div id="empty" class="empty"><svg viewBox="0 0 160 72" aria-hidden="true"><rect x="1" y="4" width="158" height="12" rx="2"/><rect x="1" y="30" width="98" height="12" rx="2"/><rect x="1" y="56" width="62" height="12" rx="2"/></svg><h3>同一个文件,三种压缩方式。</h3><p>上传 WASM 文件,选择算法后开始压缩对比。</p><p class="help">所有数字来自本次实际运行,不使用预设数据。</p></div>
31
+ <div id="results" hidden><div class="file-heading"><div><h3 id="result-name"></h3><p id="original-size"></p></div><button id="export" class="secondary" disabled>导出 JSON</button></div><div id="chart" class="chart" aria-label="文件体积对比"></div><div class="table-wrap"><table><caption class="sr-only">压缩体积、压缩和解压耗时及下载结果</caption><thead><tr><th>编码 / 级别</th><th>体积</th><th>减少</th><th>压缩</th><th>解压</th><th>文件</th></tr></thead><tbody id="result-rows"></tbody></table></div><p class="verification" id="verification"></p><details><summary>SHA-256 与测量说明</summary><code id="sha"></code><p class="help">压缩后在 Node 回解,逐字节及 SHA-256 双重校验。耗时为单次本机墙钟时间,不含上传和校验;解压耗时不代表浏览器速度。体积使用 KiB / MiB。</p></details></div>
32
+ </section>
33
+ <details class="notes"><summary>压缩文件如何用于你的项目?</summary><div class="notes-body">
34
+ <p><strong>在平台中使用:</strong>直接使用压缩后的文件即可,平台会自动处理加载所需的配置,无需额外操作。</p>
35
+ <p><strong>本地开发:</strong>同样使用压缩后的文件,按下面的示例配置本地开发服务后,就能直接引用压缩文件的地址,无需手动解压。</p>
36
+ <p><strong>Vite 配置示例:</strong>将 module.wasm.br 放入 public 目录,在现有 vite.config.js / vite.config.ts 的 plugins 中合并以下插件,保留项目其他配置,然后重启开发服务。示例同时支持 module.wasm.gz 和 module.wasm.zst;文件名不同时,同步修改匹配规则和读取路径。</p>
37
+ <pre aria-label="Vite 压缩 WASM 开发服务配置"><code>import { readFile } from 'node:fs/promises';
38
+ import { join } from 'node:path';
39
+ import { defineConfig } from 'vite';
40
+
41
+ export default defineConfig({
42
+ plugins: [{
43
+ name: 'serve-compressed-wasm',
44
+ configureServer(server) {
45
+ server.middlewares.use(async (req, res, next) =&gt; {
46
+ const path = new URL(req.url || '/', 'http://localhost').pathname;
47
+ const match = /^\/module\.wasm\.(br|gz|zst)$/.exec(path);
48
+ if (!match || !['GET', 'HEAD'].includes(req.method || 'GET')) return next();
49
+
50
+ try {
51
+ const bytes = await readFile(join(
52
+ server.config.publicDir, `module.wasm.${match[1]}`
53
+ ));
54
+ const encoding = match[1] === 'gz' ? 'gzip'
55
+ : match[1] === 'zst' ? 'zstd' : 'br';
56
+ res.setHeader('Content-Type', 'application/wasm');
57
+ res.setHeader('Content-Encoding', encoding);
58
+ res.setHeader('Content-Length', bytes.length);
59
+ res.setHeader('Cache-Control', 'no-store');
60
+ res.end(req.method === 'HEAD' ? undefined : bytes);
61
+ } catch (error) {
62
+ next(error);
63
+ }
64
+ });
65
+ },
66
+ }],
67
+ });</code></pre>
68
+ <p><strong>加载示例:</strong>直接请求带压缩后缀的地址,浏览器会根据响应头解压,再交给 WebAssembly。下面的 imports 沿用项目已有的模块导入配置;如使用引擎或工具链生成的 JS 加载器,只需将它的 WASM 路径指向 /module.wasm.br,保留原有初始化方式和配套 JS 文件。</p>
69
+ <pre aria-label="加载压缩 WASM 示例"><code>// imports 使用项目已有配置,不需要添加解压逻辑。
70
+ const { instance } = await WebAssembly.instantiateStreaming(
71
+ fetch('/module.wasm.br'),
72
+ imports
73
+ );
74
+ // 继续通过 instance.exports 使用模块。</code></pre>
75
+ <p><strong>如何确认配置生效:</strong>打开浏览器 Network,检查压缩文件请求返回 200,Content-Type 为 application/wasm,Content-Encoding 与文件格式一致(.br → br、.gz → gzip、.zst → zstd)。浏览器需支持对应编码;zstd 不兼容时可改用 gzip 压缩地址。示例按不同地址提供不同编码,无需协商;若同一地址按 Accept-Encoding 返回不同版本,还需设置 Vary: Accept-Encoding。以上插件仅用于 Vite 开发服务,vite preview 或其他静态服务需单独配置。</p>
76
+ </div></details>
77
+ </div>
78
+ </div>
79
+ </main><footer><span>WASM Compression Lab</span><span>Node 原生 zlib · 无 npm 运行依赖 · 本地演示</span></footer>
80
+ </body></html>
@@ -0,0 +1,3 @@
1
+ :root{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:#172536;background:#f4f6f8;font-size:14px;line-height:1.65;--ink:#172536;--muted:#526176;--line:#d8dfe7;--blue:#263f9d;--good:#166747;--mono:ui-monospace,SFMono-Regular,Consolas,monospace}*{box-sizing:border-box}body{margin:0}button,select,input{font:inherit}button,a,select,input{touch-action:manipulation}button{cursor:pointer}button:disabled,select:disabled{cursor:not-allowed;opacity:.5}button:focus-visible,a:focus-visible,select:focus-visible,input:focus-visible,summary:focus-visible,.dropzone:focus-within{outline:3px solid #7795ee;outline-offset:4px}a{color:var(--blue);text-underline-offset:4px}h1,h2,h3,p{margin:0}h1{font-size:30px;letter-spacing:-.03em;line-height:1.4}h2{font-size:17px;font-weight:650}h3{font-size:17px;font-weight:600}svg{fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}button,select{min-height:44px;border-radius:6px;border:1px solid var(--line);background:#fff;color:var(--ink)}button:hover:not(:disabled){border-color:var(--blue);color:var(--blue)}select{width:100%;padding:9px 32px 9px 11px;font-size:13px}label:not(.check):not(.dropzone):not(.sr-only){display:block;font-size:12px;font-weight:600;margin-bottom:7px}.masthead{max-width:1360px;margin:auto;padding:0 40px;height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:20px}.brand{display:flex;align-items:center;gap:10px;text-decoration:none;font-size:20px;font-weight:750;color:var(--ink);white-space:nowrap}.brand span{font-size:16px;font-weight:550}.brand svg{width:32px;height:32px;color:var(--blue);stroke-width:2.1}.runtime{font-size:12px;color:var(--muted)}main{max-width:1360px;margin:auto;padding:0 40px}.intro{display:flex;justify-content:space-between;align-items:center;padding:36px 0 30px;gap:20px}.intro p{color:var(--muted);margin-top:9px}.local-note{color:var(--muted);font-size:12px;white-space:nowrap}.workspace{display:grid;grid-template-columns:320px minmax(0,1fr);gap:32px;align-items:start}.source-panel{background:#fff;border:1px solid var(--line);border-radius:12px;padding:23px}.source-panel h2{margin-bottom:19px}.help{font-size:12px;line-height:1.7;color:var(--muted);margin-top:8px}fieldset{border:0;border-top:1px solid var(--line);padding:18px 0 0;margin:27px 0 21px;min-width:0}legend{font-size:12px;font-weight:600;padding:0 8px 0 0}.check{display:flex;align-items:center;gap:10px;min-height:38px;cursor:pointer}.check input{accent-color:var(--blue);width:16px;height:16px}.check span{flex:1;display:flex;justify-content:space-between;gap:8px;font-size:13px}.check small{font-size:11px;color:var(--muted)}.primary{display:flex;align-items:center;justify-content:space-between;gap:15px;background:var(--blue);border-color:var(--blue);color:#fff;width:100%;padding:12px 16px;margin-top:23px;font-weight:600}.primary:hover:not(:disabled){background:#1c307d;color:white}.primary svg{width:20px;height:20px}.status{font-size:12px;margin-top:12px;color:var(--muted);min-height:21px}.status.error{color:#a32b30}.retention{border-top:1px solid var(--line);padding-top:17px;margin-top:20px;font-size:11px;color:var(--muted)}.dropzone{border:1px dashed #8c9ab2;background:#f9fafc;border-radius:8px;min-height:158px;padding:20px 10px;display:flex;position:relative;align-items:center;justify-content:center;flex-direction:column;gap:7px;cursor:pointer;text-align:center}.dropzone.drag{background:#edf1fe;border-color:var(--blue)}.dropzone svg{width:28px;height:28px;color:var(--blue);margin-bottom:6px}.dropzone strong{font-size:13px}.dropzone span{font-size:11px;color:var(--muted)}.dropzone input{position:absolute;inset:0;width:100%;height:100%;opacity:0;cursor:pointer}.evidence{min-width:0}.section-heading{display:flex;justify-content:space-between;gap:12px;align-items:center;margin:0 0 18px}.tag{font-size:11px;padding:3px 8px;background:#e9edf3;color:var(--muted);border-radius:4px;white-space:nowrap}.tag.done{color:var(--good);background:#e5f2e9}.empty{min-height:326px;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;background:#edf1f5;border-radius:10px;padding:32px}.empty svg{width:160px;height:72px;stroke:none;fill:#d0d9e7;margin-bottom:24px}.empty svg rect:nth-child(2){fill:#a4b5d9}.empty svg rect:nth-child(3){fill:var(--blue)}.empty p{color:var(--muted);margin-top:9px;font-size:13px;max-width:45ch}.empty .help{font-size:11px;margin-top:18px}.file-heading{display:flex;justify-content:space-between;gap:15px;align-items:center;padding:0 0 19px;border-bottom:1px solid var(--line)}.file-heading h3{overflow-wrap:anywhere}.file-heading p{font-size:12px;color:var(--muted);margin-top:3px}.secondary{padding:8px 13px;font-size:12px;font-weight:600;white-space:nowrap}.chart{padding:22px 0 11px;display:grid;gap:13px}.bar-row{display:grid;grid-template-columns:65px minmax(0,1fr) 82px;align-items:center;gap:12px;font-size:12px}.bar-track{height:14px;background:#e7ebf1;border-radius:2px;overflow:hidden}.bar{height:100%;background:#9aa8bc;border-radius:2px;transform-origin:left;transition:transform .6s cubic-bezier(.16,1,.3,1)}.bar.br{background:#263f9d}.bar.gzip{background:#6786a3}.bar.zstd{background:#267b72}.bar-value{text-align:right;color:var(--muted);font-family:var(--mono);font-size:11px}.table-wrap{overflow:auto;margin-top:18px}table{width:100%;border-collapse:collapse;font-size:12px;white-space:nowrap;text-align:right}th,td{padding:12px 8px;border-bottom:1px solid var(--line)}th{font-size:11px;font-weight:500;color:var(--muted);border-top:1px solid var(--line)}th:first-child,td:first-child{text-align:left;padding-left:0}td:last-child,th:last-child{padding-right:0}td:not(:first-child){font-variant-numeric:tabular-nums}td strong{font-weight:600}td small{font-size:10px;color:var(--muted);margin-left:7px}.saving{color:var(--good)}td a{font-size:11px}.verification{font-size:12px;color:var(--good);margin:16px 0 9px}details{font-size:12px;color:var(--muted)}summary{cursor:pointer;min-height:35px;display:list-item;align-content:center}details code{display:block;overflow-wrap:anywhere;font-size:10px;font-family:var(--mono);background:#eaf0f6;padding:12px;margin:8px 0}.delivery{border-top:1px solid var(--line);margin-top:30px;padding-top:24px}.delivery>p{font-size:12px;color:var(--muted)}code{font-family:var(--mono);font-size:.9em}.delivery-actions{display:flex;gap:10px;margin:15px 0 12px}.delivery-actions select{max-width:240px}pre{background:#eaf0f5;color:#253c5a;border-radius:7px;margin:0;padding:16px;font:12px/1.8 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere;min-height:96px}.notes{margin:30px 0 0;padding:14px 20px;background:#edf1f5;border-radius:8px}.notes summary{color:var(--ink);font-weight:600}.notes-body{max-width:88ch;padding:8px 0}.notes-body p+p{margin-top:12px}footer{display:flex;justify-content:space-between;gap:20px;max-width:1360px;margin:30px auto 0;padding:20px 40px;border-top:1px solid var(--line);font-size:11px;color:var(--muted)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}[hidden]{display:none!important}@media(min-width:1500px){.workspace{gap:48px;grid-template-columns:340px minmax(0,1fr)}}@media(max-width:850px){.masthead{padding:0 24px}main{padding:0 24px}.workspace{grid-template-columns:280px minmax(0,1fr);gap:24px}.source-panel{padding:18px}.intro h1{font-size:25px}.local-note{display:none}table{font-size:11px}th,td{padding:12px 5px}.delivery-actions{flex-wrap:wrap}footer{padding:20px 24px}}@media(max-width:650px){.masthead{padding:12px 18px;min-height:66px;height:auto;flex-wrap:wrap;gap:5px}.brand{font-size:18px}.brand span{font-size:14px}.runtime{font-size:10px;margin-left:42px;width:100%}main{padding:0 18px}.intro{padding:27px 0 23px}.intro h1{font-size:25px}.intro p{font-size:13px}.workspace{display:flex;flex-direction:column;gap:28px}.source-panel,.evidence{width:100%}.source-panel{padding:20px}.empty{min-height:290px;padding:24px 18px}.empty h3{font-size:16px}select{font-size:16px}.bar-row{grid-template-columns:56px minmax(0,1fr) 77px;gap:9px}.bar-value{font-size:10px}.file-heading{align-items:flex-start}.file-heading h3{font-size:15px}table{min-width:430px}.delivery-actions select{flex:1;max-width:none;min-width:170px}.notes{padding:12px 16px}footer{padding:18px;flex-direction:column;gap:4px}.check{min-height:42px}}@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}
2
+ .notes-body pre{margin:12px 0;min-height:0;white-space:pre;overflow:auto;overflow-wrap:normal}
3
+ .notes-body pre code{padding:0;margin:0;background:none;font:inherit;overflow-wrap:normal}
@@ -0,0 +1,126 @@
1
+ import http from 'node:http';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { join, basename } from 'node:path';
5
+ import { randomUUID, createHash } from 'node:crypto';
6
+ import { Worker } from 'node:worker_threads';
7
+
8
+ const root = fileURLToPath(new URL('.', import.meta.url));
9
+ const TTL = 30 * 60 * 1000;
10
+ const jobs = new Map();
11
+
12
+ export function negotiate(header, available) {
13
+ const entries = String(header ?? '').toLowerCase().split(',').map(item => {
14
+ const [name, ...params] = item.trim().split(';');
15
+ const q = params.find(p => p.trim().startsWith('q='));
16
+ const value = q ? Number(q.trim().slice(2)) : 1;
17
+ return [name, Number.isFinite(value) && value >= 0 && value <= 1 ? value : 0];
18
+ });
19
+ const weights = new Map(entries);
20
+ const quality = name => weights.has(name) ? weights.get(name)
21
+ : name === 'identity' ? (weights.get('*') === 0 ? 0 : 1) : (weights.get('*') ?? 0);
22
+ return ['br', 'zstd', 'gzip', 'identity'].filter(x => available.includes(x))
23
+ .map((encoding, i) => ({ encoding, q: quality(encoding), i }))
24
+ .filter(x => x.q > 0).sort((a, b) => b.q - a.q || a.i - b.i)[0]?.encoding;
25
+ }
26
+
27
+ function fail(status, message) { return Object.assign(new Error(message), { status }); }
28
+ function json(res, status, body) {
29
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
30
+ res.end(JSON.stringify(body));
31
+ }
32
+ async function body(req) {
33
+ const chunks = [];
34
+ for await (const chunk of req) chunks.push(chunk);
35
+ return Buffer.concat(chunks);
36
+ }
37
+ function summary(job) {
38
+ return { id: job.id, name: job.name, size: job.original.length, status: job.status,
39
+ current: job.current, error: job.error, preset: job.preset, sha256: job.sha256,
40
+ results: job.results.map(({ bytes, ...r }) => ({ ...r, size: bytes.length,
41
+ saving: 1 - bytes.length / job.original.length,
42
+ download: `/api/jobs/${job.id}/download/${r.encoding}` })) };
43
+ }
44
+ function startJob(bytes, name, preset, algorithms) {
45
+ const job = { id: randomUUID(), name, original: bytes, preset, created: Date.now(),
46
+ status: 'running', results: [], sha256: createHash('sha256').update(bytes).digest('hex') };
47
+ jobs.set(job.id, job);
48
+ const worker = new Worker(new URL('./compress-worker.mjs', import.meta.url), {
49
+ workerData: { bytes, preset, algorithms },
50
+ });
51
+ const timer = setTimeout(() => {
52
+ job.status = 'failed'; job.error = '压缩超过 120 秒,请改用快速档。'; worker.terminate();
53
+ }, 120_000);
54
+ worker.on('message', m => {
55
+ if (m.type === 'progress') job.current = m.encoding;
56
+ if (m.type === 'result') { const { type, ...result } = m; job.results.push({ ...result, bytes: Buffer.from(m.bytes) }); }
57
+ if (m.type === 'done') { job.status = 'done'; job.current = null; }
58
+ if (m.type === 'failure') { job.status = 'failed'; job.error = m.error; }
59
+ });
60
+ worker.on('error', error => { job.status = 'failed'; job.error = error.message; });
61
+ worker.on('exit', () => {
62
+ clearTimeout(timer);
63
+ if (job.status === 'running') { job.status = 'failed'; job.error = '压缩进程意外退出,请重试。'; }
64
+ });
65
+ return job;
66
+ }
67
+
68
+ export function createApp() {
69
+ return http.createServer(async (req, res) => {
70
+ res.setHeader('X-Content-Type-Options', 'nosniff');
71
+ try {
72
+ const url = new URL(req.url, 'http://localhost');
73
+ if (req.method === 'POST') {
74
+ const origin = req.headers.origin;
75
+ if (origin && origin !== `http://${req.headers.host}`) throw fail(403, '不接受跨站请求。');
76
+ if (url.pathname !== '/api/jobs') throw fail(404, '接口不存在');
77
+ for (const [id, job] of jobs) if (job.status !== 'running' && Date.now() - job.created > TTL) jobs.delete(id);
78
+ if ([...jobs.values()].some(j => j.status === 'running')) throw fail(429, '已有压缩任务进行中,请稍后重试。');
79
+ if (jobs.size >= 6) throw fail(429, '已达到 6 个任务上限。结果保留 30 分钟,也可重启服务清空。');
80
+ const preset = url.searchParams.get('preset') ?? 'fast';
81
+ if (!['fast', 'archive'].includes(preset)) throw fail(400, '无效的压缩档位');
82
+ const algorithms = [...new Set((url.searchParams.get('algorithms') ?? 'br,gzip,zstd').split(','))];
83
+ if (!algorithms.length || algorithms.some(a => !['br', 'gzip', 'zstd'].includes(a))) throw fail(400, '请选择有效的压缩算法');
84
+ const bytes = await body(req);
85
+ let name = basename(url.searchParams.get('name') ?? 'module.wasm').replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 160);
86
+ if (!name.endsWith('.wasm')) name += '.wasm';
87
+ if (bytes.length < 8 || bytes.subarray(0, 8).toString('hex') !== '0061736d01000000') throw fail(400, '不是有效的 WebAssembly core 二进制(需要 .wasm v1 文件)。');
88
+ json(res, 202, summary(startJob(bytes, name, preset, algorithms))); return;
89
+ }
90
+ if (req.method !== 'GET' && req.method !== 'HEAD') throw fail(405, '不支持此方法');
91
+ if (url.pathname === '/api/status') {
92
+ json(res, 200, { node: process.version, maxBytes: null }); return;
93
+ }
94
+ const match = url.pathname.match(/^\/api\/jobs\/([a-f0-9-]+)(?:\/(download|module)\/([a-z]+))?$/);
95
+ if (match) {
96
+ const job = jobs.get(match[1]);
97
+ if (!job || Date.now() - job.created > TTL) throw fail(404, '任务已过期,请重新压缩。');
98
+ if (!match[2]) { json(res, 200, summary(job)); return; }
99
+ const kind = match[2], requested = match[3];
100
+ const available = ['identity', ...job.results.map(r => r.encoding)];
101
+ const encoding = kind === 'module' && requested === 'auto'
102
+ ? negotiate(req.headers['accept-encoding'], available) : requested;
103
+ if (!encoding) throw fail(406, '没有可接受的编码');
104
+ if (kind === 'module' && requested !== 'auto' && negotiate(req.headers['accept-encoding'], [encoding]) !== encoding) throw fail(406, '当前浏览器未声明支持该编码,请换用 gzip 或自动协商。');
105
+ const bytes = encoding === 'identity' ? job.original : job.results.find(r => r.encoding === encoding)?.bytes;
106
+ if (!bytes) throw fail(404, '此压缩结果尚未生成');
107
+ const ext = { br: '.br', gzip: '.gz', zstd: '.zst', identity: '' }[encoding];
108
+ const headers = { 'Content-Type': kind === 'module' ? 'application/wasm' : 'application/octet-stream',
109
+ 'Content-Length': bytes.length, 'Cache-Control': 'no-store', 'Vary': 'Accept-Encoding' };
110
+ if (kind === 'download') headers['Content-Disposition'] = `attachment; filename="${job.name}${ext}"`;
111
+ else if (encoding !== 'identity') headers['Content-Encoding'] = encoding;
112
+ res.writeHead(200, headers); res.end(req.method === 'HEAD' ? undefined : bytes); return;
113
+ }
114
+ const files = { '/': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/style.css': ['style.css', 'text/css; charset=utf-8'] };
115
+ if (!files[url.pathname]) throw fail(404, '页面不存在');
116
+ const [file, type] = files[url.pathname];
117
+ res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" });
118
+ res.end(req.method === 'HEAD' ? undefined : await readFile(join(root, 'public', file)));
119
+ } catch (error) { if (!res.headersSent) json(res, error.status ?? 500, { error: error.status ? error.message : '服务端处理失败,请查看终端日志。' }); else res.end(); if (!error.status) console.error(error); }
120
+ });
121
+ }
122
+
123
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
124
+ const port = Number(process.env.PORT ?? 8787);
125
+ createApp().listen(port, '127.0.0.1', () => console.log(`WASM Compression Lab: http://127.0.0.1:${port}`));
126
+ }
@@ -0,0 +1,45 @@
1
+ ---
2
+ name: hupu-web-security-audit
3
+ description: 用于审计虎扑 Web 项目的 HTML、JavaScript、TypeScript、CSS、SVG、图片引用、前端资源加载、浏览器请求与客户端安全问题,与 Shaper 发布安全门禁保持一致,只报告已确认的禁止项。
4
+ ---
5
+
6
+ # Role
7
+
8
+ 你是虎扑 Shaper 活动页前端安全审计工程师,只做只读静态审查,不修改代码。
9
+
10
+ # Goal
11
+
12
+ 检查活动页 HTML、JavaScript/TypeScript、CSS/预处理器、SVG 及源码中的图片与媒体引用,识别绕过统一 SDK 的请求、非批准域名资源或接口,以及能证明的客户端安全漏洞。只输出已确认的禁止项;没有发现时只输出:`未发现禁止项。`
13
+
14
+ # Context
15
+
16
+ - 检测范围:HTML、JavaScript/TypeScript、CSS/预处理器、SVG,以及源码中的图片和媒体引用。
17
+ - 域名要求:活动页加载的资源和调用的接口必须属于 `hupu.com`、`hoopchina.com.cn`、`static.cloudbase.net` 或其子域名。
18
+ - 结果要求:只输出已确认的禁止项,不输出允许项、通过项、忽略项、检查清单或泛化加固建议。
19
+
20
+ # 核心检查(与发布安全门禁一致)
21
+
22
+ 按下列优先级检查,命中即报告。每个问题必须包含严重级别、文件与行号、最小证据、具体风险和最小修复建议;同一根因合并为一个问题。
23
+
24
+ 1. **请求统一 SDK**:业务网络请求必须调用 `window.ShaperAI.request`。直接使用 `fetch`、`XMLHttpRequest`、Axios/请求库、`WebSocket`、`EventSource`、`sendBeacon` 发起业务请求 → 阻断。普通非网络 JSBridge(`HupuBridge`、`er.*`)不适用;tracker 埋点(如 `new Image().src` 指向 `hermes.hupu.com`)放行,除非外传敏感数据。
25
+ 2. **域名白名单**:远程资源与接口 hostname 必须是 `hupu.com`、`hoopchina.com.cn`、`static.cloudbase.net` 或其子域。解析 URL 的 hostname 后判断,协议相对 URL 按网络 URL 处理,`srcset` 逐项检查;严禁字符串包含判断(`hupu.com.evil.test`、`evil-hupu.com`、`hupu.com@evil.test` 均属外域)。`localhost`、回环/内网 IP、裸 IP、测试域名 → 阻断。不要把整个 `cloudbase.net` 当作批准域;`docs.cloudbase.net` 等非 `static.cloudbase.net` 子域仍属外域。`app.tcloudbase.com` 及其子域是 CloudBase 网关,不是批准静态资源域。
26
+ 3. **内联脚本与行内事件**:HTML 可执行 `<script>`、`on*=` 行内事件、`javascript:` URL、危险 `data:`/`blob:` 载荷 → 阻断。非执行块(`importmap`、`application/json`、`application/ld+json`)放行,其中 URL 仍按域名白名单检查。
27
+ 4. **动态代码执行**:可控数据进入 `eval`、`Function`、字符串计时器、动态 `import()`、`WebAssembly` 或 base64 解码后执行 → 阻断。
28
+ 5. **页面行为**:创建 `<iframe>`/`<object>`/`<embed>`、`window.open`/`target="_blank"`(未防 `window.opener`)、下载、`location` 跳转或表单提交到非批准外部 URL、可控 URL 未校验协议和 hostname → 阻断或复核。
29
+ 6. **敏感设备能力**:`navigator.geolocation`/`clipboard`/`bluetooth`/`usb`/`hid`/`serial`、传感器(`Accelerometer`/`Gyroscope`/`Magnetometer`/`DeviceMotionEvent`/`DeviceOrientationEvent`)、屏幕捕获与全屏 API → 阻断。
30
+ 7. **XSS / DOM 注入**:未经可靠净化的可控数据进入 `innerHTML`、`outerHTML`、`insertAdjacentHTML`、`document.write`、`srcdoc`、`dangerouslySetInnerHTML`、`v-html` 或 HTML 解析入口 → 阻断。
31
+ 8. **敏感信息与存储**:前端硬编码有效密码、私钥、访问令牌、会话凭证或特权 API 密钥;敏感数据发送到外域或写入 URL、日志、错误上报;`localStorage`/`sessionStorage`/Cookie 明文持久化敏感凭证;JavaScript 创建认证 Cookie → 阻断。
32
+ 9. **消息与跨窗口通信**:消息处理器未精确校验 `event.origin`、`event.source` 和消息结构就执行跳转、DOM 写入、请求、存储、鉴权、下载等敏感操作;通过 `postMessage(..., "*")` 发送敏感数据 → 阻断或复核。
33
+ 10. **请求滥用**:对请求做无条件循环、无限轮询、失败后自动重试、自动翻页超过 5 页 → 阻断或复核。
34
+
35
+ # 判定规则
36
+
37
+ - 只报告能从源码和上下文证明的禁止项;不得仅凭危险 API 名称、未知变量或缺少可选加固措施报问题。
38
+ - 常量/静态模板、测试字符串、示例占位符、不可用凭证不报告。
39
+ - 二次封装、动态拼接、压缩代码无法证明最终调用链时,按需人工复核处理,不直接定性。
40
+ - 每个问题必须包含严重级别、文件与行号、最小证据、具体风险和最小修复建议;同一根因合并。
41
+ - 不要自动修改代码,除非用户明确要求修复。
42
+
43
+ # Runtime 说明
44
+
45
+ 以静态源码审计为主。优先使用 `rg` 定位 URL、资源属性、请求 API、危险 DOM API 和代码执行入口,再阅读完整上下文并追踪局部常量、模板字符串、字符串拼接和简单封装后得出结论。不执行代码、不联网、不启动预览。
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "虎扑 Web 安全审计"
3
+ short_description: "审计虎扑活动页前端资源、网络请求与客户端安全确认禁止项"
4
+ default_prompt: "使用 $hupu-web-security-audit 审计当前活动页前端代码,只报告已确认的禁止项。"
@@ -0,0 +1,13 @@
1
+ # 激励与金币
2
+
3
+ 激励视频、机会与金币结算。本目录仅分类,技能内容暂不重构。
4
+
5
+ - [hupu-vacoin](hupu-vacoin/SKILL.md)
6
+ - [hupu-vacoin-consume-coins](hupu-vacoin-consume-coins/SKILL.md)
7
+ - [hupu-vacoin-get-coin-overview](hupu-vacoin-get-coin-overview/SKILL.md)
8
+ - [hupu-vacoin-get-session-coins](hupu-vacoin-get-session-coins/SKILL.md)
9
+ - [hupu-vacoin-reset-session-id](hupu-vacoin-reset-session-id/SKILL.md)
10
+ - [hupu-vatask](hupu-vatask/SKILL.md)
11
+ - [hupu-vatask-complete-reward-video](hupu-vatask-complete-reward-video/SKILL.md)
12
+ - [hupu-vatask-consume-activity-chance](hupu-vatask-consume-activity-chance/SKILL.md)
13
+ - [hupu-vatask-get-activity-task-state](hupu-vatask-get-activity-task-state/SKILL.md)
@@ -0,0 +1,70 @@
1
+ ---
2
+ name: hupu-vacoin
3
+ description: 为你的活动接入虎扑金币能力:查询用户金币账户、消费金币、结算玩法会话金币,并在结算后开启新一轮会话。
4
+ ---
5
+
6
+ # 金币能力(业务介绍)
7
+
8
+ 为活动页接入虎扑金币玩法:用户可查看当前金币余额,在明确交互后消费金币,并在一轮玩法结束时查询本轮累计金币。金币账户和会话由平台及 SDK 管理,业务页面无需处理用户身份或会话 id。
9
+
10
+ ## 实现指引(供生成代码的 AI 使用)
11
+
12
+ 本能力组由四个金币子能力组成,具体参数、返回值与约束如下:
13
+
14
+ | 子 Skill | JS Path | 作用 |
15
+ | --- | --- | --- |
16
+ | 查询金币余额 | `window.ShaperAI.vacoin.getCoinOverview()` | 查询当前用户余额、今日获得和今日消耗 |
17
+ | 消费金币 | `window.ShaperAI.vacoin.consumeCoins(params)` | 按指定数量扣除当前用户金币 |
18
+ | 查询本轮会话金币 | `window.ShaperAI.vacoin.getSessionCoins()` | 查询当前玩法会话累计获得的金币 |
19
+ | 开启新一轮会话 | `window.ShaperAI.vacoin.resetSessionId()` | 重置金币结算与激励归因共用的会话 id |
20
+
21
+ ### 金币能力如何运行
22
+
23
+ 1. **查询余额**:页面初始化、消费金币后或用户主动刷新时调用 `getCoinOverview()`。成功时读取 `data.overview.balance`、`todayEarned` 和 `todayConsumed`;失败时 `data.overview` 为 `null`,不能当作余额为 0。余额入口可用固定地址 `https://m.hupu.com/pdt/welfare-center` 通过 `window.ShaperAI.navigate.to({ url })` 打开福利中心。
24
+ 2. **消费金币**:用户明确点击兑换、抽奖等操作时调用 `consumeCoins({ coins, desc? })`。`coins` 必须是正整数,`desc` 只能是简短固定文案;仅 `code === 200` 且 `data.consumed === true` 表示扣费完成。成功或失败后都应刷新余额,余额是否充足由后端裁决。
25
+ 3. **结算本轮金币**:本轮玩法结束后调用 `getSessionCoins()`,会话 id 由 SDK 内部维护并与激励视频归因共用,页面不能传入或自行管理。成功时 `data.coins` 为非负数,`0` 是合法结果;展示结果后必须立即调用 `resetSessionId()` 开启下一轮,查询失败时不能重置。
26
+
27
+ ### 参数与返回约定
28
+
29
+ - `getCoinOverview()` 和 `getSessionCoins()` 不接受参数。余额查询成功返回 `data.overview`:`{ puid, balance, todayEarned, todayConsumed }`;本轮结算成功返回 `data.coins`。请求失败时前者的 `overview`、后者的 `coins` 都为 `null`,并带 `reason: "REQUEST_FAILED"`;响应格式异常时 `reason` 为 `"INVALID_RESPONSE"`。
30
+ - `consumeCoins({ coins, desc? })` 中 `coins` 必须是正整数,`desc` 可选且应为简短固定文案。参数非法会直接返回 `code: 400`、`data.consumed: false`、`reason: "INVALID_COINS"`,不会发出请求;后端拒绝或请求失败时 `consumed` 为 `false`,`reason` 为 `"REQUEST_FAILED"` 或 `"INVALID_RESPONSE"`,后端业务码可能出现在 `backendCode`。
31
+ - `resetSessionId()` 不接受参数、不发起请求,恒定返回 `{ code: 200, message: "success", data: null }`;只能在本轮金币成功结算并展示后调用。
32
+
33
+ ### 通用接入示例
34
+
35
+ ```javascript
36
+ // 查询并展示余额
37
+ const overviewRes = await window.ShaperAI.vacoin.getCoinOverview();
38
+ if (overviewRes.code === 200) {
39
+ renderBalance(overviewRes.data.overview.balance);
40
+ } else {
41
+ showMessage(overviewRes.message);
42
+ }
43
+
44
+ // 用户点击消费金币
45
+ const consumeRes = await window.ShaperAI.vacoin.consumeCoins({
46
+ coins: 50,
47
+ desc: '抽奖消费'
48
+ });
49
+ await window.ShaperAI.vacoin.getCoinOverview();
50
+ if (consumeRes.code !== 200 || !consumeRes.data.consumed) {
51
+ showMessage(consumeRes.message);
52
+ }
53
+
54
+ // 结算本轮并开启下一轮
55
+ const roundRes = await window.ShaperAI.vacoin.getSessionCoins();
56
+ if (roundRes.code === 200) {
57
+ showRoundCoins(roundRes.data.coins);
58
+ await window.ShaperAI.vacoin.resetSessionId();
59
+ }
60
+ ```
61
+
62
+ ### 通用约束
63
+
64
+ - 只允许通过 `window.ShaperAI.vacoin.*` 调用,禁止直接请求金币接口或调用原生 Bridge
65
+ - `getCoinOverview()` 和 `getSessionCoins()` 可在页面初始化、业务流程完成后或用户主动刷新时调用;禁止在循环、轮询或自动重试中高频调用
66
+ - `consumeCoins()` 必须由用户点击等明确交互触发,消费进行中必须禁用触发按钮;SDK 不做重复消费去重,一次交互只允许发起一次
67
+ - `coins` 必须是正整数;`desc` 必须使用简短固定文案,禁止拼接报错信息、模型输出等动态内容,因为它会出现在用户可见的金币流水中
68
+ - 禁止向任何能力传入 `puid`、会话 id 或活动 id 等身份/上下文参数;这些信息由请求凭证、SDK 或底座配置维护
69
+ - 失败时使用返回的 `message` 提示用户;失败的余额查询不能当作余额为 0,余额是否充足由后端裁决
70
+ - `getSessionCoins()` 成功并展示本轮结果后,必须立即调用 `resetSessionId()`;查询失败时禁止重置,否则会导致下一轮累加上一轮金币