@chainlesschain/personal-data-hub 0.4.29 → 0.4.31

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 (199) hide show
  1. package/lib/forensics/qq-nt-collect.js +190 -0
  2. package/lib/prompt-builder.js +15 -1
  3. package/package.json +8 -3
  4. package/__tests__/adapter-guide.test.js +0 -47
  5. package/__tests__/adapter-spec.test.js +0 -78
  6. package/__tests__/adapters/ai-chat-cookie-capture-spec.test.js +0 -211
  7. package/__tests__/adapters/ai-chat-health-checker.test.js +0 -262
  8. package/__tests__/adapters/ai-chat-history.test.js +0 -396
  9. package/__tests__/adapters/ai-chat-http-client.test.js +0 -242
  10. package/__tests__/adapters/ai-chat-vendors.test.js +0 -874
  11. package/__tests__/adapters/alipay-bill-adapter.test.js +0 -538
  12. package/__tests__/adapters/apple-health.test.js +0 -95
  13. package/__tests__/adapters/bank-family.test.js +0 -125
  14. package/__tests__/adapters/biz-tianyancha.test.js +0 -159
  15. package/__tests__/adapters/browser-history-chrome.test.js +0 -377
  16. package/__tests__/adapters/browser-history-edge.test.js +0 -159
  17. package/__tests__/adapters/car-mercedesme.test.js +0 -74
  18. package/__tests__/adapters/doc-baidu-netdisk.test.js +0 -102
  19. package/__tests__/adapters/doc-camscanner.test.js +0 -147
  20. package/__tests__/adapters/doc-platforms.test.js +0 -177
  21. package/__tests__/adapters/edu-huawei-learning-live.test.js +0 -198
  22. package/__tests__/adapters/edu-zuoyebang-live.test.js +0 -226
  23. package/__tests__/adapters/email-adapter-snapshot.test.js +0 -237
  24. package/__tests__/adapters/email-adapter.test.js +0 -742
  25. package/__tests__/adapters/email-classifier.test.js +0 -347
  26. package/__tests__/adapters/email-imap-session.test.js +0 -334
  27. package/__tests__/adapters/email-parser.test.js +0 -244
  28. package/__tests__/adapters/email-pdf-extractor.test.js +0 -529
  29. package/__tests__/adapters/email-providers.test.js +0 -84
  30. package/__tests__/adapters/email-retry-progress.test.js +0 -294
  31. package/__tests__/adapters/email-templates.test.js +0 -822
  32. package/__tests__/adapters/family-23-collectors-scaffold.test.js +0 -182
  33. package/__tests__/adapters/finance-alipay-live.test.js +0 -258
  34. package/__tests__/adapters/finance-dcep.test.js +0 -74
  35. package/__tests__/adapters/fitness-joyrun.test.js +0 -82
  36. package/__tests__/adapters/game-genshin-live.test.js +0 -238
  37. package/__tests__/adapters/game-genshin-scaffold.test.js +0 -108
  38. package/__tests__/adapters/game-honor-of-kings-live.test.js +0 -230
  39. package/__tests__/adapters/git-activity.test.js +0 -222
  40. package/__tests__/adapters/gov-12123.test.js +0 -103
  41. package/__tests__/adapters/gov-ixiamen.test.js +0 -150
  42. package/__tests__/adapters/gov-tax.test.js +0 -135
  43. package/__tests__/adapters/health-meiyou.test.js +0 -125
  44. package/__tests__/adapters/local-files.test.js +0 -264
  45. package/__tests__/adapters/local-im-pc.test.js +0 -154
  46. package/__tests__/adapters/messaging-whatsapp.test.js +0 -289
  47. package/__tests__/adapters/music-kugou.test.js +0 -187
  48. package/__tests__/adapters/music-qq.test.js +0 -112
  49. package/__tests__/adapters/netease-music-live.test.js +0 -244
  50. package/__tests__/adapters/netease-music.test.js +0 -74
  51. package/__tests__/adapters/pc-local-discovery.test.js +0 -141
  52. package/__tests__/adapters/qq-pc-direct-read.test.js +0 -227
  53. package/__tests__/adapters/reading-family.test.js +0 -108
  54. package/__tests__/adapters/recruit-boss.test.js +0 -180
  55. package/__tests__/adapters/shell-history.test.js +0 -180
  56. package/__tests__/adapters/shopping-base.test.js +0 -179
  57. package/__tests__/adapters/shopping-dianping.test.js +0 -239
  58. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +0 -721
  59. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +0 -346
  60. package/__tests__/adapters/social-bilibili-adb-collector.test.js +0 -284
  61. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +0 -343
  62. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +0 -296
  63. package/__tests__/adapters/social-csdn.test.js +0 -175
  64. package/__tests__/adapters/social-dongchedi.test.js +0 -165
  65. package/__tests__/adapters/social-douyin-adb-aweme-detail.test.js +0 -165
  66. package/__tests__/adapters/social-douyin-adb-collector.test.js +0 -254
  67. package/__tests__/adapters/social-douyin-adb-db-extension.test.js +0 -114
  68. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +0 -304
  69. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +0 -216
  70. package/__tests__/adapters/social-douyin-adb-usage-profile.test.js +0 -229
  71. package/__tests__/adapters/social-douyin-adb-watch-history.test.js +0 -269
  72. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +0 -496
  73. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +0 -276
  74. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +0 -152
  75. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +0 -178
  76. package/__tests__/adapters/social-toutiao-adb-account-reader.test.js +0 -135
  77. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +0 -626
  78. package/__tests__/adapters/social-toutiao-adb-article.test.js +0 -155
  79. package/__tests__/adapters/social-toutiao-adb-collector.test.js +0 -378
  80. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +0 -193
  81. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +0 -196
  82. package/__tests__/adapters/social-toutiao-kuaishou-scaffold.test.js +0 -311
  83. package/__tests__/adapters/social-weibo-adb-api-client.test.js +0 -362
  84. package/__tests__/adapters/social-weibo-adb-collector.test.js +0 -201
  85. package/__tests__/adapters/social-weibo-adb-cookies-extension.test.js +0 -167
  86. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +0 -189
  87. package/__tests__/adapters/social-xiaohongshu-adb-api-client.test.js +0 -431
  88. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +0 -207
  89. package/__tests__/adapters/social-xiaohongshu-adb-cookies-extension.test.js +0 -0
  90. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +0 -351
  91. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +0 -130
  92. package/__tests__/adapters/social-xiaohongshu-adb-snapshot-builder.test.js +0 -200
  93. package/__tests__/adapters/social-zhihu.test.js +0 -246
  94. package/__tests__/adapters/system-data-adapter.test.js +0 -443
  95. package/__tests__/adapters/system-data-android-ingest.test.js +0 -144
  96. package/__tests__/adapters/system-data-android.test.js +0 -519
  97. package/__tests__/adapters/system-data-disclosure.test.js +0 -153
  98. package/__tests__/adapters/travel-12306.test.js +0 -512
  99. package/__tests__/adapters/travel-amap.test.js +0 -219
  100. package/__tests__/adapters/travel-baidu-map.test.js +0 -305
  101. package/__tests__/adapters/travel-base.test.js +0 -205
  102. package/__tests__/adapters/travel-ctrip.test.js +0 -377
  103. package/__tests__/adapters/travel-didi-consumer.test.js +0 -66
  104. package/__tests__/adapters/travel-didi.test.js +0 -204
  105. package/__tests__/adapters/travel-tencent-map.test.js +0 -207
  106. package/__tests__/adapters/travel-tongcheng.test.js +0 -289
  107. package/__tests__/adapters/video-platforms.test.js +0 -152
  108. package/__tests__/adapters/video-xigua.test.js +0 -106
  109. package/__tests__/adapters/vscode.test.js +0 -299
  110. package/__tests__/adapters/wechat-bootstrap.test.js +0 -240
  111. package/__tests__/adapters/wechat-env-probe.test.js +0 -162
  112. package/__tests__/adapters/wechat-frida-agent.test.js +0 -322
  113. package/__tests__/adapters/wechat-frida-integration.test.js +0 -149
  114. package/__tests__/adapters/wechat-frida-key-provider.test.js +0 -188
  115. package/__tests__/adapters/wechat-md5-key-provider.test.js +0 -101
  116. package/__tests__/adapters/wechat-pc-direct-read.test.js +0 -365
  117. package/__tests__/adapters/wechat-pc-group-topic.test.js +0 -63
  118. package/__tests__/adapters/wechat-pc-v4-sidecar.test.js +0 -72
  119. package/__tests__/adapters/weread.test.js +0 -123
  120. package/__tests__/adapters/wework-pc.test.js +0 -124
  121. package/__tests__/adapters/win-recent.test.js +0 -192
  122. package/__tests__/analysis-skills.test.js +0 -754
  123. package/__tests__/analysis.test.js +0 -1845
  124. package/__tests__/audio-ximalaya-snapshot.test.js +0 -279
  125. package/__tests__/batch.test.js +0 -133
  126. package/__tests__/bridges-cc-kg.test.js +0 -231
  127. package/__tests__/bridges-cc-llm.test.js +0 -191
  128. package/__tests__/bridges-cc-rag.test.js +0 -162
  129. package/__tests__/categories.test.js +0 -92
  130. package/__tests__/e2e/ai-chat-cross-source-journey.test.js +0 -213
  131. package/__tests__/e2e/full-user-journey.test.js +0 -188
  132. package/__tests__/e2e/local-data-adapters-cli.e2e.test.js +0 -146
  133. package/__tests__/entity-resolver-ingest-hook.test.js +0 -177
  134. package/__tests__/entity-resolver-stages.test.js +0 -411
  135. package/__tests__/entity-resolver-vault.test.js +0 -249
  136. package/__tests__/entity-resolver.test.js +0 -526
  137. package/__tests__/fitness-keep-snapshot.test.js +0 -224
  138. package/__tests__/fixtures/entity-resolver-200-mock.json +0 -96
  139. package/__tests__/ids.test.js +0 -45
  140. package/__tests__/integration/ai-chat-history-registry.test.js +0 -228
  141. package/__tests__/integration/aichat-wizard-end-to-end.test.js +0 -282
  142. package/__tests__/integration/cross-adapter-pipelines.test.js +0 -396
  143. package/__tests__/integration/local-data-adapters-pipeline.test.js +0 -373
  144. package/__tests__/integration/social-bilibili-pipeline.test.js +0 -261
  145. package/__tests__/integration/wechat-bootstrap-end-to-end.test.js +0 -390
  146. package/__tests__/key-providers.test.js +0 -126
  147. package/__tests__/kg-derive.test.js +0 -219
  148. package/__tests__/llm-client.test.js +0 -122
  149. package/__tests__/longtail-adapters.test.js +0 -281
  150. package/__tests__/messaging-qq-snapshot.test.js +0 -294
  151. package/__tests__/mobile-extractor-encrypted.test.js +0 -460
  152. package/__tests__/mobile-extractor.test.js +0 -288
  153. package/__tests__/mock-adapter.test.js +0 -93
  154. package/__tests__/prompt-builder.test.js +0 -249
  155. package/__tests__/query-parser.test.js +0 -365
  156. package/__tests__/rag-derive.test.js +0 -169
  157. package/__tests__/registry-readiness.test.js +0 -292
  158. package/__tests__/registry.test.js +0 -420
  159. package/__tests__/salvage-ingest.test.js +0 -97
  160. package/__tests__/schemas.test.js +0 -331
  161. package/__tests__/shopping-adapters.test.js +0 -392
  162. package/__tests__/shopping-eleme-snapshot.test.js +0 -454
  163. package/__tests__/shopping-pinduoduo-snapshot.test.js +0 -484
  164. package/__tests__/shopping-snapshot.test.js +0 -438
  165. package/__tests__/shopping-vipshop-snapshot.test.js +0 -425
  166. package/__tests__/shopping-xianyu-snapshot.test.js +0 -451
  167. package/__tests__/sidecar-contacts-cross-validate.test.js +0 -186
  168. package/__tests__/sidecar-supervisor.test.js +0 -128
  169. package/__tests__/sign-providers.test.js +0 -62
  170. package/__tests__/social-adapters.test.js +0 -280
  171. package/__tests__/social-bilibili-snapshot.test.js +0 -278
  172. package/__tests__/social-douban-snapshot.test.js +0 -351
  173. package/__tests__/social-douyin-im-direct-read.test.js +0 -377
  174. package/__tests__/social-douyin-salvage-collector.test.js +0 -98
  175. package/__tests__/social-douyin-salvage-mapper.test.js +0 -90
  176. package/__tests__/social-douyin-snapshot.test.js +0 -256
  177. package/__tests__/social-kuaishou-snapshot.test.js +0 -362
  178. package/__tests__/social-toutiao-snapshot.test.js +0 -366
  179. package/__tests__/social-weibo-snapshot.test.js +0 -234
  180. package/__tests__/social-weibo-sqlite-device.test.js +0 -174
  181. package/__tests__/social-xiaohongshu-snapshot.test.js +0 -232
  182. package/__tests__/sqlite-leaf-salvage.test.js +0 -97
  183. package/__tests__/travel-adapters.test.js +0 -483
  184. package/__tests__/travel-maps-snapshot.test.js +0 -426
  185. package/__tests__/vault-driver-error.test.js +0 -74
  186. package/__tests__/vault-search-helpers.test.js +0 -104
  187. package/__tests__/vault-search.test.js +0 -423
  188. package/__tests__/vault.test.js +0 -767
  189. package/__tests__/wechat-adapter.test.js +0 -594
  190. package/__tests__/whatsapp-adapter.test.js +0 -138
  191. package/scripts/_make-fixture-all.js +0 -126
  192. package/scripts/_make-fixture-contacts.js +0 -84
  193. package/scripts/evaluate-entity-resolver.js +0 -213
  194. package/scripts/run-native-tests-sandbox.sh +0 -55
  195. package/scripts/smoke-phase-5-5.js +0 -196
  196. package/scripts/smoke-phase-5-7.js +0 -181
  197. package/scripts/smoke-system-data-contacts.js +0 -309
  198. package/scripts/smoke-system-data.js +0 -312
  199. package/vitest.config.js +0 -88
@@ -1,198 +0,0 @@
1
- /**
2
- * FAMILY-23 v0.2 — edu-huawei-learning LIVE web fetcher tests.
3
- * cookie (华为账号会话) → user-info + study-records → snapshot-shaped events +
4
- * adapter live sync + defensive field extraction + error mapping.
5
- * All network via injected fetch. Endpoint shapes are best-effort (see
6
- * api-client header) — these tests pin the REQUEST CONSTRUCTION + PARSING
7
- * contract, not the live server, which can't be verified here.
8
- */
9
- "use strict";
10
-
11
- import { describe, it, expect } from "vitest";
12
-
13
- const { HuaweiLearningAdapter } = require("../../lib");
14
- const {
15
- HuaweiLearningApiClient,
16
- } = require("../../lib/adapters/edu-huawei-learning/api-client");
17
- const { validateBatch } = require("../../lib/batch");
18
-
19
- const COOKIE = "accountId=555; CASTGC=tok-xyz";
20
-
21
- function makeFetch(routes, calls) {
22
- return async (url, init) => {
23
- calls.push({ url, headers: (init && init.headers) || {} });
24
- const route = routes.find((r) => url.includes(r.match));
25
- if (!route) return { ok: false, status: 404, text: async () => "not mapped" };
26
- return {
27
- ok: route.status ? route.status >= 200 && route.status < 300 : true,
28
- status: route.status || 200,
29
- text: async () =>
30
- typeof route.body === "string" ? route.body : JSON.stringify(route.body),
31
- };
32
- };
33
- }
34
-
35
- async function collect(iter) {
36
- const out = [];
37
- for await (const r of iter) out.push(r);
38
- return out;
39
- }
40
-
41
- describe("HuaweiLearningApiClient session probe", () => {
42
- it("hasSession is lenient: any k=v cookie passes, empty/garbage fails", () => {
43
- const c = new HuaweiLearningApiClient();
44
- expect(c.hasSession("CASTGC=tok")).toBe(true);
45
- expect(c.hasSession(COOKIE)).toBe(true);
46
- expect(c.hasSession("")).toBe(false);
47
- expect(c.lastError.code).toBe(-7);
48
- expect(c.hasSession("garbage")).toBe(false);
49
- });
50
- });
51
-
52
- describe("HuaweiLearningApiClient.fetchSnapshot — live (mocked fetch)", () => {
53
- it("carries cookie on each GET + parses user/records defensively", async () => {
54
- const calls = [];
55
- const fetch = makeFetch(
56
- [
57
- {
58
- match: "/edu/api/user/v1/info",
59
- body: { code: 0, data: { user: { accountId: 555, nickName: "小华" } } },
60
- },
61
- {
62
- match: "/edu/api/study/v1/records",
63
- body: {
64
- code: 0,
65
- data: {
66
- records: [
67
- { recordId: "c1", courseName: "物理", studyDuration: 1500, startTime: 1700000000 },
68
- { id: "c2", title: "化学", duration: 600000, createTime: "1700003600" },
69
- ],
70
- },
71
- },
72
- },
73
- ],
74
- calls,
75
- );
76
- const client = new HuaweiLearningApiClient({ fetch });
77
- const result = await client.fetchSnapshot(COOKIE);
78
- expect(result.account).toEqual({ uid: "555", displayName: "小华" });
79
- const profile = result.events.find((e) => e.kind === "profile");
80
- expect(profile).toMatchObject({ uid: "555", nickname: "小华" });
81
- const studies = result.events.filter((e) => e.kind === "study");
82
- expect(studies).toHaveLength(2);
83
- expect(studies[0]).toMatchObject({ id: "study-c1", course: "物理", durationMs: 1500000, startAt: 1700000000000 });
84
- expect(studies[1]).toMatchObject({ id: "study-c2", course: "化学", durationMs: 600000, startAt: 1700003600000 });
85
- for (const c of calls) {
86
- expect(c.headers.Cookie).toBe(COOKIE);
87
- }
88
- });
89
-
90
- it("handles alternate envelope (resultCode + result + list)", async () => {
91
- const fetch = makeFetch(
92
- [
93
- { match: "/edu/api/user/v1/info", body: { resultCode: 0, result: { userId: "999", displayName: "阿福" } } },
94
- { match: "/edu/api/study/v1/records", body: { resultCode: 0, result: { list: [{ logId: "z1", name: "数学", learnTime: 300 }] } } },
95
- ],
96
- [],
97
- );
98
- const client = new HuaweiLearningApiClient({ fetch });
99
- const result = await client.fetchSnapshot(COOKIE);
100
- expect(result.account).toEqual({ uid: "999", displayName: "阿福" });
101
- const study = result.events.find((e) => e.kind === "study");
102
- expect(study).toMatchObject({ id: "study-z1", course: "数学", durationMs: 300000 });
103
- });
104
-
105
- it("include.study:false skips records; limit/offset land in the query", async () => {
106
- const calls = [];
107
- const fetch = makeFetch(
108
- [
109
- { match: "/edu/api/user/v1/info", body: { code: 0, data: { accountId: 1, nickName: "x" } } },
110
- { match: "/edu/api/study/v1/records", body: { code: 0, data: { records: [] } } },
111
- ],
112
- calls,
113
- );
114
- const client = new HuaweiLearningApiClient({ fetch });
115
- await client.fetchSnapshot(COOKIE, { include: { study: false } });
116
- expect(calls.some((c) => c.url.includes("/study/v1/records"))).toBe(false);
117
-
118
- await client.fetchSnapshot(COOKIE, { limit: 7, offset: 3 });
119
- const rec = calls.find((c) => c.url.includes("/study/v1/records"));
120
- expect(rec.url).toContain("offset=3");
121
- expect(rec.url).toContain("limit=7");
122
- });
123
-
124
- it("maps non-zero code to null + lastError", async () => {
125
- const fetch = makeFetch(
126
- [{ match: "/edu/api/user/v1/info", body: { code: 401, message: "会话过期" } }],
127
- [],
128
- );
129
- const client = new HuaweiLearningApiClient({ fetch });
130
- expect(await client.fetchSnapshot(COOKIE)).toBeNull();
131
- expect(client.lastError.code).toBe(401);
132
- expect(client.lastError.message).toContain("会话过期");
133
- });
134
-
135
- it("no session cookie → null + lastError -7 (no network)", async () => {
136
- const calls = [];
137
- const client = new HuaweiLearningApiClient({ fetch: makeFetch([], calls) });
138
- expect(await client.fetchSnapshot("")).toBeNull();
139
- expect(client.lastError.code).toBe(-7);
140
- expect(calls).toHaveLength(0);
141
- });
142
-
143
- it("HTTP non-2xx → null + lastError with status", async () => {
144
- const fetch = makeFetch([{ match: "/edu/api/user/v1/info", status: 500, body: "err" }], []);
145
- const client = new HuaweiLearningApiClient({ fetch });
146
- expect(await client.fetchSnapshot(COOKIE)).toBeNull();
147
- expect(client.lastError.code).toBe(500);
148
- });
149
- });
150
-
151
- describe("HuaweiLearningAdapter — cookie (live) sync mode", () => {
152
- it("authenticate accepts a session cookie; rejects empty", async () => {
153
- const a = new HuaweiLearningAdapter();
154
- expect((await a.authenticate({ cookie: COOKIE })).mode).toBe("cookie");
155
- const bad = await a.authenticate({ cookie: "garbage" });
156
- expect(bad.ok).toBe(false);
157
- expect(bad.reason).toBe("INVALID_COOKIE");
158
- });
159
-
160
- it("version/capabilities reflect v0.2 live mode", () => {
161
- const a = new HuaweiLearningAdapter();
162
- expect(a.version).toBe("0.2.0");
163
- expect(a.capabilities).toContain("sync:cookie");
164
- });
165
-
166
- it("sync via cookie yields profile+study raws → valid normalized batch", async () => {
167
- const fetch = makeFetch(
168
- [
169
- { match: "/edu/api/user/v1/info", body: { code: 0, data: { accountId: 555, nickName: "小华" } } },
170
- { match: "/edu/api/study/v1/records", body: { code: 0, data: { records: [{ recordId: "c1", courseName: "物理", studyDuration: 1500, startTime: 1700000000 }] } } },
171
- ],
172
- [],
173
- );
174
- const a = new HuaweiLearningAdapter();
175
- const raws = await collect(a.sync({ cookie: COOKIE, fetch }));
176
- expect(raws.map((r) => r.kind).sort()).toEqual(["profile", "study"]);
177
- const profileRaw = raws.find((r) => r.kind === "profile");
178
- expect(profileRaw.originalId).toBe("huaweilearning:profile:profile-555");
179
-
180
- for (const raw of raws) {
181
- expect(validateBatch(a.normalize(raw)).valid).toBe(true);
182
- }
183
- const profileBatch = a.normalize(profileRaw);
184
- expect(profileBatch.persons[0].identifiers["huawei-learning-uid"]).toEqual(["555"]);
185
- const studyBatch = a.normalize(raws.find((r) => r.kind === "study"));
186
- expect(studyBatch.events[0].extra.course).toBe("物理");
187
- expect(studyBatch.events[0].extra.durationMs).toBe(1500000);
188
- });
189
-
190
- it("sync via cookie throws (mapped lastError) on API error", async () => {
191
- const fetch = makeFetch(
192
- [{ match: "/edu/api/user/v1/info", body: { code: 401, message: "会话过期" } }],
193
- [],
194
- );
195
- const a = new HuaweiLearningAdapter();
196
- await expect(collect(a.sync({ cookie: COOKIE, fetch }))).rejects.toThrow(/会话过期|code 401/);
197
- });
198
- });
@@ -1,226 +0,0 @@
1
- /**
2
- * FAMILY-23 v0.2 — edu-zuoyebang LIVE web fetcher tests.
3
- * cookie (ZYBUSS 会话) → user-info + study-records → snapshot-shaped events +
4
- * adapter live sync + defensive field extraction + error mapping.
5
- * All network via injected fetch. Endpoint shapes are best-effort (see
6
- * api-client header) — these tests pin the REQUEST CONSTRUCTION + PARSING
7
- * contract, not the live server, which can't be verified here.
8
- */
9
- "use strict";
10
-
11
- import { describe, it, expect } from "vitest";
12
-
13
- const { ZuoyebangAdapter } = require("../../lib");
14
- const {
15
- ZuoyebangApiClient,
16
- } = require("../../lib/adapters/edu-zuoyebang/api-client");
17
- const {
18
- pick,
19
- toDurationMs,
20
- toEpochMs,
21
- } = require("../../lib/adapters/_live-json-helpers");
22
- const { validateBatch } = require("../../lib/batch");
23
-
24
- const COOKIE = "ZYBUSS=opaquetoken123; other=1";
25
-
26
- function makeFetch(routes, calls) {
27
- return async (url, init) => {
28
- calls.push({ url, headers: (init && init.headers) || {} });
29
- const route = routes.find((r) => url.includes(r.match));
30
- if (!route) return { ok: false, status: 404, text: async () => "not mapped" };
31
- return {
32
- ok: route.status ? route.status >= 200 && route.status < 300 : true,
33
- status: route.status || 200,
34
- text: async () =>
35
- typeof route.body === "string" ? route.body : JSON.stringify(route.body),
36
- };
37
- };
38
- }
39
-
40
- async function collect(iter) {
41
- const out = [];
42
- for await (const r of iter) out.push(r);
43
- return out;
44
- }
45
-
46
- describe("_live-json-helpers (shared field-extraction)", () => {
47
- it("pick returns first present non-empty value", () => {
48
- expect(pick({ a: "", b: "x" }, ["a", "b"])).toBe("x");
49
- expect(pick({ a: 0 }, ["a"])).toBe(0); // 0 is present
50
- expect(pick({}, ["a"], "fb")).toBe("fb");
51
- expect(pick(null, ["a"], "fb")).toBe("fb");
52
- });
53
-
54
- it("toDurationMs disambiguates seconds vs ms; coerces numeric strings", () => {
55
- expect(toDurationMs(1800)).toBe(1800000);
56
- expect(toDurationMs(1800000)).toBe(1800000);
57
- expect(toDurationMs("900")).toBe(900000);
58
- expect(toDurationMs("nope")).toBe(0);
59
- });
60
-
61
- it("toEpochMs coerces seconds/ms/date-string", () => {
62
- expect(toEpochMs(1700000000)).toBe(1700000000000);
63
- expect(toEpochMs("1700000000000")).toBe(1700000000000);
64
- expect(toEpochMs("2023-11-14T22:13:20Z")).toBe(1700000000000);
65
- expect(toEpochMs("bogus")).toBeNull();
66
- });
67
- });
68
-
69
- describe("ZuoyebangApiClient session probe", () => {
70
- it("hasSession accepts ZYBUSS-only cookie (uid comes from the API)", () => {
71
- const c = new ZuoyebangApiClient();
72
- expect(c.hasSession("ZYBUSS=opaque")).toBe(true);
73
- expect(c.hasSession("uid=111")).toBe(true);
74
- expect(c.hasSession("foo=bar")).toBe(false);
75
- expect(c.lastError.code).toBe(-7);
76
- expect(c.hasSession("")).toBe(false);
77
- });
78
- });
79
-
80
- describe("ZuoyebangApiClient.fetchSnapshot — live (mocked fetch)", () => {
81
- it("carries cookie on each GET + parses user/records defensively", async () => {
82
- const calls = [];
83
- const fetch = makeFetch(
84
- [
85
- {
86
- match: "/session/pc/getuserinfo",
87
- body: { errNo: 0, data: { user: { uid: 12345, uname: "小红", gradeName: "初二" } } },
88
- },
89
- {
90
- match: "/study/pc/record/list",
91
- body: {
92
- errNo: 0,
93
- data: {
94
- list: [
95
- { recordId: "r1", subjectName: "数学", studyTime: 1200, startTime: 1700000000 },
96
- { logId: "r2", subject: "英语", duration: 900000, createTime: "1700003600" },
97
- ],
98
- },
99
- },
100
- },
101
- ],
102
- calls,
103
- );
104
- const client = new ZuoyebangApiClient({ fetch });
105
- const result = await client.fetchSnapshot(COOKIE);
106
- expect(result.account).toEqual({ uid: "12345", displayName: "小红" });
107
- const profile = result.events.find((e) => e.kind === "profile");
108
- expect(profile).toMatchObject({ uid: "12345", nickname: "小红", grade: "初二" });
109
- const studies = result.events.filter((e) => e.kind === "study");
110
- expect(studies).toHaveLength(2);
111
- expect(studies[0]).toMatchObject({ id: "study-r1", subject: "数学", durationMs: 1200000, startAt: 1700000000000 });
112
- expect(studies[1]).toMatchObject({ id: "study-r2", subject: "英语", durationMs: 900000, startAt: 1700003600000 });
113
- for (const c of calls) {
114
- expect(c.headers.Cookie).toBe(COOKIE);
115
- }
116
- });
117
-
118
- it("handles flat user body + alternate envelope key (errno)", async () => {
119
- const calls = [];
120
- const fetch = makeFetch(
121
- [
122
- { match: "/session/pc/getuserinfo", body: { errno: 0, data: { userId: "888", nickName: "阿明" } } },
123
- { match: "/study/pc/record/list", body: { errno: 0, data: { records: [] } } },
124
- ],
125
- calls,
126
- );
127
- const client = new ZuoyebangApiClient({ fetch });
128
- const result = await client.fetchSnapshot(COOKIE);
129
- expect(result.account).toEqual({ uid: "888", displayName: "阿明" });
130
- });
131
-
132
- it("include.study:false skips the records call; limit/offset map to rn/pn", async () => {
133
- const calls = [];
134
- const fetch = makeFetch(
135
- [
136
- { match: "/session/pc/getuserinfo", body: { errNo: 0, data: { uid: 1, uname: "x" } } },
137
- { match: "/study/pc/record/list", body: { errNo: 0, data: { list: [] } } },
138
- ],
139
- calls,
140
- );
141
- const client = new ZuoyebangApiClient({ fetch });
142
- await client.fetchSnapshot(COOKIE, { include: { study: false } });
143
- expect(calls.some((c) => c.url.includes("record/list"))).toBe(false);
144
-
145
- await client.fetchSnapshot(COOKIE, { limit: 5, offset: 2 });
146
- const rec = calls.find((c) => c.url.includes("record/list"));
147
- expect(rec.url).toContain("pn=2");
148
- expect(rec.url).toContain("rn=5");
149
- });
150
-
151
- it("maps non-zero errNo to null + lastError (e.g. session expired)", async () => {
152
- const fetch = makeFetch(
153
- [{ match: "/session/pc/getuserinfo", body: { errNo: 3, errstr: "未登录" } }],
154
- [],
155
- );
156
- const client = new ZuoyebangApiClient({ fetch });
157
- expect(await client.fetchSnapshot(COOKIE)).toBeNull();
158
- expect(client.lastError.code).toBe(3);
159
- expect(client.lastError.message).toContain("未登录");
160
- });
161
-
162
- it("no session cookie → null + lastError -7 (no network)", async () => {
163
- const calls = [];
164
- const client = new ZuoyebangApiClient({ fetch: makeFetch([], calls) });
165
- expect(await client.fetchSnapshot("foo=bar")).toBeNull();
166
- expect(client.lastError.code).toBe(-7);
167
- expect(calls).toHaveLength(0);
168
- });
169
-
170
- it("HTTP non-2xx → null + lastError with status", async () => {
171
- const fetch = makeFetch([{ match: "/session/pc/getuserinfo", status: 503, body: "down" }], []);
172
- const client = new ZuoyebangApiClient({ fetch });
173
- expect(await client.fetchSnapshot(COOKIE)).toBeNull();
174
- expect(client.lastError.code).toBe(503);
175
- });
176
- });
177
-
178
- describe("ZuoyebangAdapter — cookie (live) sync mode", () => {
179
- it("authenticate accepts ZYBUSS cookie; rejects sessionless", async () => {
180
- const a = new ZuoyebangAdapter();
181
- expect((await a.authenticate({ cookie: COOKIE })).mode).toBe("cookie");
182
- const bad = await a.authenticate({ cookie: "foo=bar" });
183
- expect(bad.ok).toBe(false);
184
- expect(bad.reason).toBe("INVALID_COOKIE");
185
- });
186
-
187
- it("version/capabilities reflect v0.2 live mode", () => {
188
- const a = new ZuoyebangAdapter();
189
- expect(a.version).toBe("0.2.0");
190
- expect(a.capabilities).toContain("sync:cookie");
191
- });
192
-
193
- it("sync via cookie yields profile+study raws → valid normalized batch", async () => {
194
- const fetch = makeFetch(
195
- [
196
- { match: "/session/pc/getuserinfo", body: { errNo: 0, data: { user: { uid: 12345, uname: "小红", gradeName: "初二" } } } },
197
- { match: "/study/pc/record/list", body: { errNo: 0, data: { list: [{ recordId: "r1", subjectName: "数学", studyTime: 1200, startTime: 1700000000 }] } } },
198
- ],
199
- [],
200
- );
201
- const a = new ZuoyebangAdapter();
202
- const raws = await collect(a.sync({ cookie: COOKIE, fetch }));
203
- expect(raws.map((r) => r.kind).sort()).toEqual(["profile", "study"]);
204
- const profileRaw = raws.find((r) => r.kind === "profile");
205
- expect(profileRaw.originalId).toBe("zuoyebang:profile:profile-12345");
206
-
207
- for (const raw of raws) {
208
- expect(validateBatch(a.normalize(raw)).valid).toBe(true);
209
- }
210
- const profileBatch = a.normalize(profileRaw);
211
- expect(profileBatch.persons[0].identifiers["zuoyebang-uid"]).toEqual(["12345"]);
212
- expect(profileBatch.persons[0].extra.grade).toBe("初二");
213
- const studyBatch = a.normalize(raws.find((r) => r.kind === "study"));
214
- expect(studyBatch.events[0].extra.subject).toBe("数学");
215
- expect(studyBatch.events[0].extra.durationMs).toBe(1200000);
216
- });
217
-
218
- it("sync via cookie throws (mapped lastError) on API error", async () => {
219
- const fetch = makeFetch(
220
- [{ match: "/session/pc/getuserinfo", body: { errNo: 3, errstr: "未登录" } }],
221
- [],
222
- );
223
- const a = new ZuoyebangAdapter();
224
- await expect(collect(a.sync({ cookie: COOKIE, fetch }))).rejects.toThrow(/未登录|code 3/);
225
- });
226
- });
@@ -1,237 +0,0 @@
1
- "use strict";
2
-
3
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
4
-
5
- const fs = require("node:fs");
6
- const os = require("node:os");
7
- const path = require("node:path");
8
-
9
- const {
10
- EmailAdapter,
11
- } = require("../../lib/adapters/email-imap/email-adapter");
12
- const { assertAdapter } = require("../../lib/adapter-spec");
13
-
14
- /**
15
- * Phase 5.8 — snapshot mode for Android EmailLocalCollector ingestion.
16
- *
17
- * EmailLocalCollector.kt (android-app) does the IMAP fetch on-device with
18
- * Jakarta Mail, then writes filesDir/staging/email-<vendor>-<ts>.json with
19
- * shape `{vendor, user, fetchedAt, records: [{messageNumber, subject, from,
20
- * to, sentDateMs, bodyPreview, hasAttachments}]}`. The desktop EmailAdapter
21
- * must consume that JSON via syncAdapter("email-imap", path) — without it
22
- * the UI shows "v0.2 补齐 (邮件已成功抓 X 封到本机临时区)" misleading hint
23
- * because the local fetch worked but cc couldn't ingest it.
24
- *
25
- * snapshotMode opt:
26
- * - Relaxes opts.account.email + authCode constructor validation
27
- * - Switches authenticate(ctx.inputPath) to file-readability check
28
- * - Switches sync(opts.inputPath) to read JSON + emit raw events
29
- * - Classifier + extractor still fire (text-only, no PDF since attachment
30
- * buffers never crossed Android → desktop boundary)
31
- */
32
- describe("EmailAdapter snapshot mode", () => {
33
- let tmpDir;
34
- beforeEach(() => {
35
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "email-snap-"));
36
- });
37
- afterEach(() => {
38
- try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch (_e) {}
39
- });
40
-
41
- it("snapshotMode constructor accepts no opts.account", () => {
42
- const a = new EmailAdapter({ snapshotMode: true });
43
- expect(a.name).toBe("email-imap");
44
- expect(a.capabilities).toContain("sync:snapshot");
45
- expect(a.capabilities).not.toContain("sync:imap");
46
- expect(a.capabilities).not.toContain("auth:authcode");
47
- // Classifier + extractor capabilities preserved (snapshot still classifies)
48
- expect(a.capabilities).toContain("classify:layer1-rules");
49
- expect(a.capabilities).toContain("extract:6-templates");
50
- });
51
-
52
- it("snapshotMode adapter passes contract assertion", () => {
53
- const a = new EmailAdapter({ snapshotMode: true });
54
- const r = assertAdapter(a);
55
- if (!r.ok) console.log("assertAdapter errors:", r.errors);
56
- expect(r.ok).toBe(true);
57
- });
58
-
59
- it("authenticate(ctx.inputPath) returns ok when file readable", async () => {
60
- const inputPath = path.join(tmpDir, "snap.json");
61
- fs.writeFileSync(inputPath, "{}", "utf-8");
62
- const a = new EmailAdapter({ snapshotMode: true });
63
- const auth = await a.authenticate({ inputPath });
64
- expect(auth.ok).toBe(true);
65
- expect(auth.mode).toBe("snapshot-file");
66
- });
67
-
68
- it("authenticate without inputPath in snapshotMode returns NO_INPUT", async () => {
69
- const a = new EmailAdapter({ snapshotMode: true });
70
- const auth = await a.authenticate({});
71
- expect(auth.ok).toBe(false);
72
- expect(auth.reason).toBe("NO_INPUT");
73
- });
74
-
75
- it("authenticate with unreadable inputPath returns INPUT_PATH_UNREADABLE", async () => {
76
- const a = new EmailAdapter({ snapshotMode: true });
77
- const auth = await a.authenticate({ inputPath: path.join(tmpDir, "nope.json") });
78
- expect(auth.ok).toBe(false);
79
- expect(auth.reason).toBe("INPUT_PATH_UNREADABLE");
80
- });
81
-
82
- it("sync(inputPath) yields one raw event per record", async () => {
83
- const inputPath = path.join(tmpDir, "snap.json");
84
- fs.writeFileSync(inputPath, JSON.stringify({
85
- vendor: "qq",
86
- user: "user@qq.com",
87
- fetchedAt: 1_700_000_000_000,
88
- records: [
89
- {
90
- messageNumber: 1,
91
- subject: "Test subject 1",
92
- from: "Alice <alice@x.com>",
93
- to: "user@qq.com",
94
- sentDateMs: 1_700_000_100_000,
95
- bodyPreview: "hello world",
96
- hasAttachments: false,
97
- },
98
- {
99
- messageNumber: 2,
100
- subject: "Order confirmation",
101
- from: "noreply@shop.com",
102
- to: "user@qq.com",
103
- sentDateMs: 1_700_000_200_000,
104
- bodyPreview: "your order ABC123 has shipped",
105
- hasAttachments: true,
106
- },
107
- ],
108
- }), "utf-8");
109
-
110
- const a = new EmailAdapter({ snapshotMode: true });
111
- const raws = [];
112
- for await (const r of a.sync({ inputPath })) raws.push(r);
113
- expect(raws).toHaveLength(2);
114
-
115
- expect(raws[0].adapter).toBe("email-imap");
116
- expect(raws[0].originalId).toBe("android-snapshot:qq:user@qq.com:1");
117
- expect(raws[0].capturedAt).toBe(1_700_000_100_000);
118
- expect(raws[0].payload.subject).toBe("Test subject 1");
119
- expect(raws[0].payload.from[0].address).toBe("alice@x.com");
120
- expect(raws[0].payload.from[0].name).toBe("Alice");
121
- expect(raws[0].payload.to[0].address).toBe("user@qq.com");
122
- expect(raws[0].payload.folder).toBe("INBOX");
123
- // Classification fires even on envelope-only data
124
- expect(raws[0].payload.classification).toBeDefined();
125
- expect(raws[0].payload.classification.category).toBeDefined();
126
-
127
- expect(raws[1].originalId).toBe("android-snapshot:qq:user@qq.com:2");
128
- expect(raws[1].payload.from[0].address).toBe("noreply@shop.com");
129
- // hasAttachments=true → parsedBody.attachments has placeholder entry
130
- expect(raws[1].payload.parsedBody.attachments).toHaveLength(1);
131
- });
132
-
133
- it("sync(inputPath) on empty records emits nothing", async () => {
134
- const inputPath = path.join(tmpDir, "empty.json");
135
- fs.writeFileSync(inputPath, JSON.stringify({
136
- vendor: "163",
137
- user: "u@163.com",
138
- fetchedAt: Date.now(),
139
- records: [],
140
- }), "utf-8");
141
-
142
- const a = new EmailAdapter({ snapshotMode: true });
143
- const raws = [];
144
- for await (const r of a.sync({ inputPath })) raws.push(r);
145
- expect(raws).toHaveLength(0);
146
- });
147
-
148
- it("sync(inputPath) on malformed JSON throws clear error", async () => {
149
- const inputPath = path.join(tmpDir, "bad.json");
150
- fs.writeFileSync(inputPath, "{not json", "utf-8");
151
-
152
- const a = new EmailAdapter({ snapshotMode: true });
153
- let threw = null;
154
- try {
155
- for await (const _r of a.sync({ inputPath })) { /* drain */ }
156
- } catch (err) {
157
- threw = err;
158
- }
159
- expect(threw).toBeTruthy();
160
- expect(threw.message).toMatch(/bad JSON/);
161
- });
162
-
163
- it("sync(inputPath) without records[] throws shape error", async () => {
164
- const inputPath = path.join(tmpDir, "noshape.json");
165
- fs.writeFileSync(inputPath, JSON.stringify({ vendor: "qq" }), "utf-8");
166
-
167
- const a = new EmailAdapter({ snapshotMode: true });
168
- let threw = null;
169
- try {
170
- for await (const _r of a.sync({ inputPath })) { /* drain */ }
171
- } catch (err) {
172
- threw = err;
173
- }
174
- expect(threw).toBeTruthy();
175
- expect(threw.message).toMatch(/records/);
176
- });
177
-
178
- it("sync(opts.limit) respected on snapshot record iteration", async () => {
179
- const inputPath = path.join(tmpDir, "many.json");
180
- const records = [];
181
- for (let i = 1; i <= 10; i += 1) {
182
- records.push({
183
- messageNumber: i,
184
- subject: `msg ${i}`,
185
- from: `s${i}@x.com`,
186
- to: "u@q.com",
187
- sentDateMs: 1_700_000_000_000 + i * 1000,
188
- bodyPreview: `body ${i}`,
189
- hasAttachments: false,
190
- });
191
- }
192
- fs.writeFileSync(inputPath, JSON.stringify({
193
- vendor: "qq",
194
- user: "u@q.com",
195
- fetchedAt: Date.now(),
196
- records,
197
- }), "utf-8");
198
-
199
- const a = new EmailAdapter({ snapshotMode: true });
200
- const raws = [];
201
- for await (const r of a.sync({ inputPath, limit: 3 })) raws.push(r);
202
- expect(raws).toHaveLength(3);
203
- });
204
-
205
- it("sync(inputPath) handles records with no sentDateMs (falls back to fetchedAt)", async () => {
206
- const inputPath = path.join(tmpDir, "nodate.json");
207
- fs.writeFileSync(inputPath, JSON.stringify({
208
- vendor: "qq",
209
- user: "u@q.com",
210
- fetchedAt: 1_700_500_000_000,
211
- records: [
212
- {
213
- messageNumber: 1,
214
- subject: "no date",
215
- from: "x@x.com",
216
- to: "u@q.com",
217
- // sentDateMs intentionally omitted
218
- bodyPreview: "",
219
- hasAttachments: false,
220
- },
221
- ],
222
- }), "utf-8");
223
-
224
- const a = new EmailAdapter({ snapshotMode: true });
225
- const raws = [];
226
- for await (const r of a.sync({ inputPath })) raws.push(r);
227
- expect(raws).toHaveLength(1);
228
- expect(raws[0].capturedAt).toBe(1_700_500_000_000);
229
- });
230
-
231
- it("non-snapshot mode still requires opts.account (preserves Phase 5.1 invariant)", () => {
232
- expect(() => new EmailAdapter({})).toThrow(/account/);
233
- expect(() => new EmailAdapter({ account: { email: "u@x.com" } })).toThrow(/authCode/);
234
- // But snapshot mode bypasses both:
235
- expect(() => new EmailAdapter({ snapshotMode: true })).not.toThrow();
236
- });
237
- });