@chainlesschain/personal-data-hub 0.3.1 → 0.3.7

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 (79) hide show
  1. package/__tests__/adapters/email-adapter-snapshot.test.js +237 -0
  2. package/__tests__/adapters/email-adapter.test.js +1 -1
  3. package/__tests__/adapters/email-pdf-extractor.test.js +1 -1
  4. package/__tests__/adapters/email-retry-progress.test.js +1 -1
  5. package/__tests__/adapters/email-templates.test.js +1 -1
  6. package/__tests__/adapters/social-bilibili-adb-api-client.test.js +721 -0
  7. package/__tests__/adapters/social-bilibili-adb-chromium-cookies-reader.test.js +346 -0
  8. package/__tests__/adapters/social-bilibili-adb-collector.test.js +284 -0
  9. package/__tests__/adapters/social-bilibili-adb-cookies-extension.test.js +343 -0
  10. package/__tests__/adapters/social-bilibili-adb-snapshot-builder.test.js +296 -0
  11. package/__tests__/adapters/social-douyin-adb-collector.test.js +254 -0
  12. package/__tests__/adapters/social-douyin-adb-im-db-parser.test.js +304 -0
  13. package/__tests__/adapters/social-douyin-adb-snapshot-builder.test.js +216 -0
  14. package/__tests__/adapters/social-kuaishou-adb-api-client.test.js +432 -0
  15. package/__tests__/adapters/social-kuaishou-adb-collector.test.js +276 -0
  16. package/__tests__/adapters/social-kuaishou-adb-cookies-extension.test.js +141 -0
  17. package/__tests__/adapters/social-kuaishou-adb-snapshot-builder.test.js +178 -0
  18. package/__tests__/adapters/social-toutiao-adb-api-client.test.js +537 -0
  19. package/__tests__/adapters/social-toutiao-adb-collector.test.js +285 -0
  20. package/__tests__/adapters/social-toutiao-adb-cookies-extension.test.js +163 -0
  21. package/__tests__/adapters/social-toutiao-adb-snapshot-builder.test.js +196 -0
  22. package/__tests__/adapters/social-weibo-adb-api-client.test.js +362 -0
  23. package/__tests__/adapters/social-weibo-adb-collector.test.js +201 -0
  24. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +189 -0
  25. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +207 -0
  26. package/__tests__/adapters/social-xiaohongshu-adb-sign-provider-injection.test.js +351 -0
  27. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +130 -0
  28. package/__tests__/adapters/system-data-android.test.js +32 -1
  29. package/__tests__/longtail-adapters.test.js +15 -2
  30. package/__tests__/shopping-adapters.test.js +96 -0
  31. package/__tests__/sign-providers.test.js +62 -0
  32. package/__tests__/travel-adapters.test.js +66 -0
  33. package/__tests__/whatsapp-adapter.test.js +5 -2
  34. package/lib/adapters/browser-history-chrome/chrome-db-reader.js +11 -1
  35. package/lib/adapters/email-imap/email-adapter.js +224 -17
  36. package/lib/adapters/messaging-telegram/index.js +15 -12
  37. package/lib/adapters/messaging-whatsapp/index.js +15 -12
  38. package/lib/adapters/shopping-taobao/index.js +161 -21
  39. package/lib/adapters/social-bilibili-adb/api-client.js +555 -0
  40. package/lib/adapters/social-bilibili-adb/chromium-cookies-reader.js +296 -0
  41. package/lib/adapters/social-bilibili-adb/collector.js +190 -0
  42. package/lib/adapters/social-bilibili-adb/cookies-extension.js +250 -0
  43. package/lib/adapters/social-bilibili-adb/index.js +51 -0
  44. package/lib/adapters/social-bilibili-adb/snapshot-builder.js +197 -0
  45. package/lib/adapters/social-douyin/index.js +4 -0
  46. package/lib/adapters/social-douyin-adb/collector.js +165 -0
  47. package/lib/adapters/social-douyin-adb/db-extension.js +281 -0
  48. package/lib/adapters/social-douyin-adb/im-db-parser.js +287 -0
  49. package/lib/adapters/social-douyin-adb/index.js +57 -0
  50. package/lib/adapters/social-douyin-adb/snapshot-builder.js +174 -0
  51. package/lib/adapters/social-kuaishou-adb/api-client.js +397 -0
  52. package/lib/adapters/social-kuaishou-adb/collector.js +196 -0
  53. package/lib/adapters/social-kuaishou-adb/cookies-extension.js +261 -0
  54. package/lib/adapters/social-kuaishou-adb/index.js +53 -0
  55. package/lib/adapters/social-kuaishou-adb/snapshot-builder.js +145 -0
  56. package/lib/adapters/social-toutiao-adb/api-client.js +377 -0
  57. package/lib/adapters/social-toutiao-adb/collector.js +200 -0
  58. package/lib/adapters/social-toutiao-adb/cookies-extension.js +266 -0
  59. package/lib/adapters/social-toutiao-adb/index.js +52 -0
  60. package/lib/adapters/social-toutiao-adb/snapshot-builder.js +148 -0
  61. package/lib/adapters/social-weibo-adb/api-client.js +281 -0
  62. package/lib/adapters/social-weibo-adb/collector.js +169 -0
  63. package/lib/adapters/social-weibo-adb/cookies-extension.js +251 -0
  64. package/lib/adapters/social-weibo-adb/index.js +55 -0
  65. package/lib/adapters/social-weibo-adb/snapshot-builder.js +145 -0
  66. package/lib/adapters/social-xiaohongshu-adb/api-client.js +309 -0
  67. package/lib/adapters/social-xiaohongshu-adb/collector.js +209 -0
  68. package/lib/adapters/social-xiaohongshu-adb/cookies-extension.js +211 -0
  69. package/lib/adapters/social-xiaohongshu-adb/index.js +50 -0
  70. package/lib/adapters/social-xiaohongshu-adb/sign.js +90 -0
  71. package/lib/adapters/social-xiaohongshu-adb/snapshot-builder.js +126 -0
  72. package/lib/adapters/system-data-android/adapter.js +77 -3
  73. package/lib/adapters/travel-amap/index.js +16 -10
  74. package/lib/adapters/travel-ctrip/index.js +25 -9
  75. package/lib/adapters/vscode/vscode-reader.js +7 -1
  76. package/lib/sign-providers/index.js +20 -0
  77. package/lib/sign-providers/interface.js +82 -0
  78. package/lib/sign-providers/null-sign-provider.js +30 -0
  79. package/package.json +10 -1
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Phase 1a (Bilibili C 路径) — unit cover for the chromium-cookies-reader.
5
+ *
6
+ * Builds a real chromium-shape Cookies sqlite via better-sqlite3 (the
7
+ * test path that browser-history-chrome.test.js uses — root Node ABI
8
+ * 127 matches plain better-sqlite3, no FTS5 / encryption needed). All
9
+ * tests run in <1s on CI.
10
+ *
11
+ * Covered:
12
+ * - hostKeyMatches across .domain / domain / subdomain / non-match
13
+ * - readChromiumCookies filtering by domain
14
+ * - Cookie schema column tolerance (encrypted_value / is_secure /
15
+ * is_persistent missing — old or aggressively-pruned WebView builds)
16
+ * - assembleBilibiliCookieHeader: complete / missing-required / dup-name
17
+ * - encrypted_value rows skipped + diagnostic counter
18
+ * - corrupted DB / wrong-schema DB → clear error
19
+ */
20
+
21
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
22
+ import { mkdtempSync, rmSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { tmpdir } from "node:os";
25
+ import Database from "better-sqlite3";
26
+
27
+ const {
28
+ readChromiumCookies,
29
+ assembleBilibiliCookieHeader,
30
+ BILIBILI_COOKIE_NAMES,
31
+ _internals,
32
+ } = require("../../lib/adapters/social-bilibili-adb/chromium-cookies-reader");
33
+
34
+ let tmpDir;
35
+ let dbPath;
36
+
37
+ beforeEach(() => {
38
+ tmpDir = mkdtempSync(join(tmpdir(), "cc-cookies-test-"));
39
+ dbPath = join(tmpDir, "Cookies");
40
+ });
41
+
42
+ afterEach(() => {
43
+ try {
44
+ rmSync(tmpDir, { recursive: true, force: true });
45
+ } catch (_e) {
46
+ // ignore — temp cleanup is best-effort
47
+ }
48
+ });
49
+
50
+ /**
51
+ * Build a chromium-shape Cookies sqlite at [dbPath]. Optionally omit
52
+ * encrypted_value column (`{omitEncrypted: true}`) to simulate older
53
+ * Android WebView schemas that didn't have it.
54
+ */
55
+ function buildCookiesFixture(rows, { omitEncrypted = false, omitSecure = false } = {}) {
56
+ const db = new Database(dbPath);
57
+ const cols = [
58
+ "creation_utc INTEGER",
59
+ "host_key TEXT",
60
+ "name TEXT",
61
+ "value TEXT",
62
+ omitEncrypted ? null : "encrypted_value BLOB",
63
+ "path TEXT",
64
+ "expires_utc INTEGER",
65
+ omitSecure ? null : "is_secure INTEGER",
66
+ "is_httponly INTEGER",
67
+ "is_persistent INTEGER",
68
+ ].filter(Boolean).join(", ");
69
+ db.exec(`CREATE TABLE cookies(${cols});`);
70
+ const params = [
71
+ "creation_utc",
72
+ "host_key",
73
+ "name",
74
+ "value",
75
+ omitEncrypted ? null : "encrypted_value",
76
+ "path",
77
+ "expires_utc",
78
+ omitSecure ? null : "is_secure",
79
+ "is_httponly",
80
+ "is_persistent",
81
+ ].filter(Boolean);
82
+ const placeholders = params.map(() => "?").join(", ");
83
+ const insert = db.prepare(
84
+ `INSERT INTO cookies(${params.join(", ")}) VALUES(${placeholders})`,
85
+ );
86
+ for (const r of rows) {
87
+ const values = [
88
+ r.creationUtc || 0,
89
+ r.hostKey,
90
+ r.name,
91
+ r.value || "",
92
+ ...(omitEncrypted ? [] : [r.encryptedValue || null]),
93
+ r.path || "/",
94
+ r.expiresUtc || 0,
95
+ ...(omitSecure ? [] : [r.isSecure ? 1 : 0]),
96
+ r.isHttpOnly ? 1 : 0,
97
+ r.isPersistent ? 1 : 0,
98
+ ];
99
+ insert.run(...values);
100
+ }
101
+ db.close();
102
+ }
103
+
104
+ // ─── hostKeyMatches ─────────────────────────────────────────────────────
105
+
106
+ describe("hostKeyMatches", () => {
107
+ it("matches exact host_key against domain", () => {
108
+ expect(_internals.hostKeyMatches("bilibili.com", "bilibili.com")).toBe(true);
109
+ });
110
+
111
+ it("matches leading-dot host_key (most common)", () => {
112
+ expect(_internals.hostKeyMatches(".bilibili.com", "bilibili.com")).toBe(true);
113
+ });
114
+
115
+ it("matches subdomain host_key", () => {
116
+ expect(_internals.hostKeyMatches(".api.bilibili.com", "bilibili.com")).toBe(true);
117
+ expect(_internals.hostKeyMatches("api.bilibili.com", "bilibili.com")).toBe(true);
118
+ });
119
+
120
+ it("matches when both have leading dot", () => {
121
+ expect(_internals.hostKeyMatches(".bilibili.com", ".bilibili.com")).toBe(true);
122
+ });
123
+
124
+ it("rejects unrelated domain", () => {
125
+ expect(_internals.hostKeyMatches(".weibo.com", "bilibili.com")).toBe(false);
126
+ });
127
+
128
+ it("rejects partial-name collisions (bilibili.com.evil.cn)", () => {
129
+ // The domain check uses dot-anchored suffix, so foo.com matching
130
+ // foo.com.evil.cn is impossible.
131
+ expect(_internals.hostKeyMatches(".bilibili.com.evil.cn", "bilibili.com")).toBe(false);
132
+ });
133
+
134
+ it("rejects null / undefined / empty", () => {
135
+ expect(_internals.hostKeyMatches(null, "bilibili.com")).toBe(false);
136
+ expect(_internals.hostKeyMatches(".bilibili.com", null)).toBe(false);
137
+ expect(_internals.hostKeyMatches("", "bilibili.com")).toBe(false);
138
+ });
139
+ });
140
+
141
+ // ─── readChromiumCookies ────────────────────────────────────────────────
142
+
143
+ describe("readChromiumCookies", () => {
144
+ it("returns only cookies matching the domain filter", () => {
145
+ buildCookiesFixture([
146
+ { hostKey: ".bilibili.com", name: "SESSDATA", value: "abc123" },
147
+ { hostKey: ".weibo.com", name: "SUB", value: "wbxx" },
148
+ { hostKey: ".bilibili.com", name: "bili_jct", value: "csrf456" },
149
+ ]);
150
+ const out = readChromiumCookies(dbPath, "bilibili.com");
151
+ expect(out).toHaveLength(2);
152
+ expect(out.map((r) => r.name).sort()).toEqual(["SESSDATA", "bili_jct"]);
153
+ });
154
+
155
+ it("handles subdomain-pinned cookies", () => {
156
+ buildCookiesFixture([
157
+ { hostKey: "api.bilibili.com", name: "PinnedCookie", value: "x" },
158
+ { hostKey: ".bilibili.com", name: "SESSDATA", value: "y" },
159
+ ]);
160
+ const out = readChromiumCookies(dbPath, "bilibili.com");
161
+ expect(out).toHaveLength(2);
162
+ });
163
+
164
+ it("skips encrypted_value rows + reports count", () => {
165
+ buildCookiesFixture([
166
+ { hostKey: ".bilibili.com", name: "SESSDATA", value: "plain" },
167
+ {
168
+ hostKey: ".bilibili.com",
169
+ name: "EncryptedThing",
170
+ value: "", // empty plaintext
171
+ encryptedValue: Buffer.from("garbled-bytes"),
172
+ },
173
+ ]);
174
+ const out = readChromiumCookies(dbPath, "bilibili.com");
175
+ expect(out).toHaveLength(1);
176
+ expect(out[0].name).toBe("SESSDATA");
177
+ expect(out._skippedEncryptedCount).toBe(1);
178
+ });
179
+
180
+ it("works on schema without encrypted_value column", () => {
181
+ buildCookiesFixture(
182
+ [{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }],
183
+ { omitEncrypted: true },
184
+ );
185
+ const out = readChromiumCookies(dbPath, "bilibili.com");
186
+ expect(out).toHaveLength(1);
187
+ expect(out[0].hasEncryptedValue).toBe(false);
188
+ });
189
+
190
+ it("works on schema without is_secure column", () => {
191
+ buildCookiesFixture(
192
+ [{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }],
193
+ { omitSecure: true },
194
+ );
195
+ const out = readChromiumCookies(dbPath, "bilibili.com");
196
+ expect(out[0].isSecure).toBe(false); // defaulted to 0 by COALESCE
197
+ });
198
+
199
+ it("converts WebKit expires_utc to epoch ms", () => {
200
+ // 2026-05-25 00:00:00 UTC = 1779999600000 ms epoch
201
+ // = 13422518400000000 µs WebKit (epoch + 11644473600 * 1e6)
202
+ const expiresMs = 1779999600000;
203
+ const expiresWk = (BigInt(expiresMs) * 1000n + 11_644_473_600_000_000n).toString();
204
+ buildCookiesFixture([
205
+ {
206
+ hostKey: ".bilibili.com",
207
+ name: "SESSDATA",
208
+ value: "x",
209
+ expiresUtc: expiresWk,
210
+ },
211
+ ]);
212
+ const out = readChromiumCookies(dbPath, "bilibili.com");
213
+ expect(out[0].expiresMs).toBe(expiresMs);
214
+ });
215
+
216
+ it("throws clear error when cookies table missing (not a Cookies DB)", () => {
217
+ const db = new Database(dbPath);
218
+ db.exec("CREATE TABLE not_cookies(x INTEGER);");
219
+ db.close();
220
+ // PRAGMA table_info(<nonexistent>) returns empty rather than throwing
221
+ // on SQLite, so we hit the "empty / unreadable" branch. Either message
222
+ // is fine for the caller's purpose — both mean "not a Cookies DB".
223
+ expect(() => readChromiumCookies(dbPath, "bilibili.com")).toThrow(
224
+ /cookies.*(table not found|table empty.*unreadable)/,
225
+ );
226
+ });
227
+
228
+ it("throws clear error when required column missing", () => {
229
+ const db = new Database(dbPath);
230
+ db.exec("CREATE TABLE cookies(creation_utc INTEGER, host_key TEXT);");
231
+ db.close();
232
+ expect(() => readChromiumCookies(dbPath, "bilibili.com")).toThrow(
233
+ /required column.*missing/,
234
+ );
235
+ });
236
+
237
+ it("rejects empty dbPath", () => {
238
+ expect(() => readChromiumCookies("", "bilibili.com")).toThrow(TypeError);
239
+ });
240
+
241
+ it("rejects empty domain", () => {
242
+ buildCookiesFixture([{ hostKey: ".bilibili.com", name: "SESSDATA", value: "x" }]);
243
+ expect(() => readChromiumCookies(dbPath, "")).toThrow(TypeError);
244
+ });
245
+ });
246
+
247
+ // ─── assembleBilibiliCookieHeader ───────────────────────────────────────
248
+
249
+ describe("assembleBilibiliCookieHeader", () => {
250
+ function cookieRow(name, value, hostKey = ".bilibili.com") {
251
+ return {
252
+ name,
253
+ value,
254
+ hostKey,
255
+ expiresMs: null,
256
+ isSecure: false,
257
+ isHttponly: true,
258
+ isPersistent: true,
259
+ hasEncryptedValue: false,
260
+ };
261
+ }
262
+
263
+ it("assembles complete header when all 5 cookies present", () => {
264
+ const cookies = [
265
+ cookieRow("SESSDATA", "abc"),
266
+ cookieRow("bili_jct", "csrf"),
267
+ cookieRow("DedeUserID", "1234"),
268
+ cookieRow("DedeUserID__ckMd5", "deadbeef"),
269
+ cookieRow("buvid3", "buvid-x"),
270
+ ];
271
+ const { header, missing, present } = assembleBilibiliCookieHeader(cookies);
272
+ expect(missing).toEqual([]);
273
+ expect(header).toBe(
274
+ "SESSDATA=abc; bili_jct=csrf; DedeUserID=1234; DedeUserID__ckMd5=deadbeef; buvid3=buvid-x",
275
+ );
276
+ expect(present).toEqual(new Set(BILIBILI_COOKIE_NAMES));
277
+ });
278
+
279
+ it("returns null header + missing list when any required cookie absent", () => {
280
+ const cookies = [
281
+ cookieRow("SESSDATA", "abc"),
282
+ cookieRow("bili_jct", "csrf"),
283
+ // missing DedeUserID, DedeUserID__ckMd5, buvid3
284
+ ];
285
+ const { header, missing } = assembleBilibiliCookieHeader(cookies);
286
+ expect(header).toBe(null);
287
+ expect(missing.sort()).toEqual(["DedeUserID", "DedeUserID__ckMd5", "buvid3"].sort());
288
+ });
289
+
290
+ it("ignores non-bilibili cookies if accidentally passed in", () => {
291
+ const cookies = [
292
+ cookieRow("SESSDATA", "abc"),
293
+ cookieRow("bili_jct", "csrf"),
294
+ cookieRow("DedeUserID", "1234"),
295
+ cookieRow("DedeUserID__ckMd5", "deadbeef"),
296
+ cookieRow("buvid3", "buvid-x"),
297
+ cookieRow("randomNoise", "ignored", ".weibo.com"),
298
+ ];
299
+ const { header } = assembleBilibiliCookieHeader(cookies);
300
+ expect(header).not.toContain("randomNoise");
301
+ expect(header).not.toContain("ignored");
302
+ });
303
+
304
+ it("prefers more-specific host_key on duplicate names", () => {
305
+ const cookies = [
306
+ cookieRow("SESSDATA", "shorter", ".bilibili.com"),
307
+ cookieRow("SESSDATA", "longer", "api.bilibili.com"), // longer host wins
308
+ cookieRow("bili_jct", "csrf"),
309
+ cookieRow("DedeUserID", "1234"),
310
+ cookieRow("DedeUserID__ckMd5", "deadbeef"),
311
+ cookieRow("buvid3", "buvid-x"),
312
+ ];
313
+ const { header } = assembleBilibiliCookieHeader(cookies);
314
+ expect(header).toContain("SESSDATA=longer");
315
+ expect(header).not.toContain("SESSDATA=shorter");
316
+ });
317
+
318
+ it("throws TypeError when given non-array", () => {
319
+ expect(() => assembleBilibiliCookieHeader(null)).toThrow(TypeError);
320
+ expect(() => assembleBilibiliCookieHeader({})).toThrow(TypeError);
321
+ });
322
+
323
+ it("returns null header for empty cookie list (all 5 missing)", () => {
324
+ const { header, missing } = assembleBilibiliCookieHeader([]);
325
+ expect(header).toBe(null);
326
+ expect(missing.length).toBe(BILIBILI_COOKIE_NAMES.length);
327
+ });
328
+ });
329
+
330
+ // ─── BILIBILI_COOKIE_NAMES contract ─────────────────────────────────────
331
+
332
+ describe("BILIBILI_COOKIE_NAMES", () => {
333
+ it("is frozen", () => {
334
+ expect(Object.isFrozen(BILIBILI_COOKIE_NAMES)).toBe(true);
335
+ });
336
+
337
+ it("contains the 5 expected names", () => {
338
+ expect(BILIBILI_COOKIE_NAMES).toEqual([
339
+ "SESSDATA",
340
+ "bili_jct",
341
+ "DedeUserID",
342
+ "DedeUserID__ckMd5",
343
+ "buvid3",
344
+ ]);
345
+ });
346
+ });
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Phase 1b — unit cover for the BilibiliAdbCollector orchestrator.
5
+ *
6
+ * Strategy: mock bridge + ApiClient + registry as plain objects so we
7
+ * verify the orchestration logic (call order, error propagation,
8
+ * partial-result tolerance, cleanup) without spawning real ADB or
9
+ * hitting api.bilibili.com.
10
+ *
11
+ * What we cover:
12
+ * - collect() — bridge.invoke → 4 fetches → snapshot file written
13
+ * - collect() returns counts + diagnostic
14
+ * - collect() rejects malformed bridge payload
15
+ * - collect() propagates bridge.invoke errors
16
+ * - collect() tolerates any-of-4 endpoint failure (partial)
17
+ * - collect() tolerates ALL 4 endpoints empty (0-event snapshot)
18
+ * - collectAndSync() — pipes snapshot to registry + always cleans up
19
+ * - collectAndSync() cleanup happens even on syncAdapter throw
20
+ */
21
+
22
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
23
+ import { existsSync, readFileSync, mkdtempSync, rmSync } from "node:fs";
24
+ import { join } from "node:path";
25
+ import { tmpdir } from "node:os";
26
+
27
+ const {
28
+ collect,
29
+ collectAndSync,
30
+ } = require("../../lib/adapters/social-bilibili-adb/collector");
31
+
32
+ let stagingDir;
33
+
34
+ beforeEach(() => {
35
+ stagingDir = mkdtempSync(join(tmpdir(), "cc-collector-test-"));
36
+ });
37
+
38
+ afterEach(() => {
39
+ try {
40
+ rmSync(stagingDir, { recursive: true, force: true });
41
+ } catch (_e) {
42
+ // ignore
43
+ }
44
+ });
45
+
46
+ function makeFakeBridge(invokeResult) {
47
+ return {
48
+ invoke: vi.fn(async () => {
49
+ if (invokeResult instanceof Error) throw invokeResult;
50
+ return invokeResult;
51
+ }),
52
+ };
53
+ }
54
+
55
+ function makeFakeApiClient({
56
+ history = [],
57
+ favourites = [],
58
+ dynamics = [],
59
+ follows = [],
60
+ lastErrorCode = 0,
61
+ lastErrorMessage = null,
62
+ } = {}) {
63
+ return {
64
+ fetchHistory: vi.fn(async () => history),
65
+ fetchFavourites: vi.fn(async () => favourites),
66
+ fetchDynamics: vi.fn(async () => dynamics),
67
+ fetchFollows: vi.fn(async () => follows),
68
+ lastErrorCode,
69
+ lastErrorMessage,
70
+ };
71
+ }
72
+
73
+ // ─── collect() ──────────────────────────────────────────────────────────
74
+
75
+ describe("collect — happy path", () => {
76
+ it("invokes bridge, fetches 4 endpoints, writes snapshot, returns counts", async () => {
77
+ const bridge = makeFakeBridge({
78
+ cookie: "SESSDATA=x; DedeUserID=1234567890; ...",
79
+ uid: 1234567890,
80
+ diagnostic: { cookieCount: 5 },
81
+ });
82
+ const apiClient = makeFakeApiClient({
83
+ history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
84
+ favourites: [{ bvid: "BVf", title: "f", savedAt: 2 }],
85
+ dynamics: [{ rid: "r1", summary: "d", dynamicType: "av", publishedAt: 3 }],
86
+ follows: [{ mid: 1, uname: "u", followedAt: 4 }],
87
+ });
88
+ const result = await collect(bridge, { apiClient, stagingDir });
89
+
90
+ expect(bridge.invoke).toHaveBeenCalledWith("bilibili.cookies");
91
+ expect(apiClient.fetchHistory).toHaveBeenCalled();
92
+ expect(apiClient.fetchFavourites).toHaveBeenCalledWith(
93
+ "SESSDATA=x; DedeUserID=1234567890; ...",
94
+ 1234567890,
95
+ expect.any(Object),
96
+ );
97
+ expect(apiClient.fetchDynamics).toHaveBeenCalled();
98
+ expect(apiClient.fetchFollows).toHaveBeenCalled();
99
+
100
+ expect(result.uid).toBe(1234567890);
101
+ expect(result.eventCounts).toEqual({
102
+ history: 1,
103
+ favourite: 1,
104
+ dynamic: 1,
105
+ follow: 1,
106
+ total: 4,
107
+ });
108
+ expect(existsSync(result.snapshotPath)).toBe(true);
109
+ const snap = JSON.parse(readFileSync(result.snapshotPath, "utf-8"));
110
+ expect(snap.schemaVersion).toBe(1);
111
+ expect(snap.events).toHaveLength(4);
112
+ expect(result.cookieDiagnostic).toEqual({ cookieCount: 5 });
113
+ });
114
+
115
+ it("forwards lastErrorCode + lastErrorMessage from api client", async () => {
116
+ const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
117
+ const apiClient = makeFakeApiClient({
118
+ lastErrorCode: -412,
119
+ lastErrorMessage: "anti-spider",
120
+ });
121
+ const result = await collect(bridge, { apiClient, stagingDir });
122
+ expect(result.lastErrorCode).toBe(-412);
123
+ expect(result.lastErrorMessage).toBe("anti-spider");
124
+ });
125
+
126
+ it("calls 4 endpoints in parallel (Promise.all)", async () => {
127
+ const order = [];
128
+ const apiClient = {
129
+ fetchHistory: async () => {
130
+ order.push("history-start");
131
+ await new Promise((r) => setTimeout(r, 10));
132
+ order.push("history-end");
133
+ return [];
134
+ },
135
+ fetchFavourites: async () => {
136
+ order.push("favourites-start");
137
+ await new Promise((r) => setTimeout(r, 10));
138
+ order.push("favourites-end");
139
+ return [];
140
+ },
141
+ fetchDynamics: async () => {
142
+ order.push("dynamics-start");
143
+ await new Promise((r) => setTimeout(r, 10));
144
+ order.push("dynamics-end");
145
+ return [];
146
+ },
147
+ fetchFollows: async () => {
148
+ order.push("follows-start");
149
+ await new Promise((r) => setTimeout(r, 10));
150
+ order.push("follows-end");
151
+ return [];
152
+ },
153
+ lastErrorCode: 0,
154
+ lastErrorMessage: null,
155
+ };
156
+ const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
157
+ await collect(bridge, { apiClient, stagingDir });
158
+ // All 4 "start" events should fire before any "end" event (parallel)
159
+ const firstEnd = order.findIndex((e) => e.endsWith("-end"));
160
+ const startsBeforeFirstEnd = order.slice(0, firstEnd).filter((e) => e.endsWith("-start"));
161
+ expect(startsBeforeFirstEnd).toHaveLength(4);
162
+ });
163
+ });
164
+
165
+ describe("collect — failure modes", () => {
166
+ it("propagates bridge.invoke error", async () => {
167
+ const bridge = makeFakeBridge(new Error("BILIBILI_NO_ROOT: ..."));
168
+ await expect(collect(bridge, { stagingDir })).rejects.toThrow(
169
+ /BILIBILI_NO_ROOT/,
170
+ );
171
+ });
172
+
173
+ it("throws TypeError when bridge missing invoke fn", async () => {
174
+ await expect(collect(null, { stagingDir })).rejects.toThrow(TypeError);
175
+ await expect(collect({}, { stagingDir })).rejects.toThrow(TypeError);
176
+ });
177
+
178
+ it("throws when bridge returns malformed payload", async () => {
179
+ const bridge = makeFakeBridge({ cookie: null, uid: null });
180
+ await expect(collect(bridge, { stagingDir })).rejects.toThrow(
181
+ /malformed payload/,
182
+ );
183
+ });
184
+
185
+ it("throws when uid is not positive", async () => {
186
+ const bridge = makeFakeBridge({ cookie: "x", uid: 0 });
187
+ await expect(collect(bridge, { stagingDir })).rejects.toThrow();
188
+ });
189
+ });
190
+
191
+ describe("collect — partial result tolerance", () => {
192
+ it("succeeds with 0 events when ALL 4 endpoints empty", async () => {
193
+ const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
194
+ const apiClient = makeFakeApiClient(); // all empty
195
+ const result = await collect(bridge, { apiClient, stagingDir });
196
+ expect(result.eventCounts.total).toBe(0);
197
+ expect(existsSync(result.snapshotPath)).toBe(true);
198
+ });
199
+
200
+ it("succeeds with partial event set when one endpoint fails (returns [])", async () => {
201
+ const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
202
+ const apiClient = makeFakeApiClient({
203
+ history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
204
+ favourites: [], // simulated failure
205
+ dynamics: [],
206
+ follows: [{ mid: 1, uname: "u", followedAt: 1 }],
207
+ });
208
+ const result = await collect(bridge, { apiClient, stagingDir });
209
+ expect(result.eventCounts).toEqual({
210
+ history: 1,
211
+ favourite: 0,
212
+ dynamic: 0,
213
+ follow: 1,
214
+ total: 2,
215
+ });
216
+ });
217
+ });
218
+
219
+ // ─── collectAndSync() ───────────────────────────────────────────────────
220
+
221
+ describe("collectAndSync — pipes to registry + cleans up", () => {
222
+ it("calls registry.syncAdapter with snapshot path + returns merged report", async () => {
223
+ const bridge = makeFakeBridge({ cookie: "x", uid: 42 });
224
+ const apiClient = makeFakeApiClient({
225
+ history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
226
+ });
227
+ let syncedPath = null;
228
+ const registry = {
229
+ syncAdapter: vi.fn(async (name, opts) => {
230
+ if (name !== "social-bilibili") throw new Error("wrong name");
231
+ syncedPath = opts.inputPath;
232
+ return {
233
+ adapter: name,
234
+ status: "ok",
235
+ rawCount: 1,
236
+ entityCounts: { events: 1, persons: 0, places: 0, items: 0, topics: 0 },
237
+ };
238
+ }),
239
+ };
240
+
241
+ const report = await collectAndSync(bridge, registry, {
242
+ apiClient,
243
+ stagingDir,
244
+ });
245
+
246
+ expect(registry.syncAdapter).toHaveBeenCalledWith("social-bilibili", {
247
+ inputPath: expect.any(String),
248
+ });
249
+ expect(syncedPath).toBeTruthy();
250
+ expect(report.status).toBe("ok");
251
+ expect(report.rawCount).toBe(1);
252
+ expect(report.bilibili.uid).toBe(42);
253
+ expect(report.bilibili.eventCounts.history).toBe(1);
254
+ // Cleanup happened: the snapshot file should be gone
255
+ expect(existsSync(syncedPath)).toBe(false);
256
+ });
257
+
258
+ it("cleans up snapshot file even when syncAdapter throws", async () => {
259
+ const bridge = makeFakeBridge({ cookie: "x", uid: 42 });
260
+ const apiClient = makeFakeApiClient();
261
+ let syncedPath = null;
262
+ const registry = {
263
+ syncAdapter: vi.fn(async (_name, opts) => {
264
+ syncedPath = opts.inputPath;
265
+ throw new Error("simulated registry failure");
266
+ }),
267
+ };
268
+ await expect(
269
+ collectAndSync(bridge, registry, { apiClient, stagingDir }),
270
+ ).rejects.toThrow("simulated registry failure");
271
+ expect(syncedPath).toBeTruthy();
272
+ expect(existsSync(syncedPath)).toBe(false); // cleanup ran
273
+ });
274
+
275
+ it("throws TypeError when registry missing syncAdapter fn", async () => {
276
+ const bridge = makeFakeBridge({ cookie: "x", uid: 1 });
277
+ await expect(
278
+ collectAndSync(bridge, null, { apiClient: makeFakeApiClient() }),
279
+ ).rejects.toThrow(TypeError);
280
+ await expect(
281
+ collectAndSync(bridge, {}, { apiClient: makeFakeApiClient() }),
282
+ ).rejects.toThrow(TypeError);
283
+ });
284
+ });