@chainlesschain/personal-data-hub 0.3.1 → 0.3.6

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 (60) 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-weibo-adb-api-client.test.js +362 -0
  15. package/__tests__/adapters/social-weibo-adb-collector.test.js +201 -0
  16. package/__tests__/adapters/social-weibo-adb-snapshot-builder.test.js +189 -0
  17. package/__tests__/adapters/social-xiaohongshu-adb-collector.test.js +207 -0
  18. package/__tests__/adapters/social-xiaohongshu-adb-sign.test.js +130 -0
  19. package/__tests__/adapters/system-data-android.test.js +32 -1
  20. package/__tests__/longtail-adapters.test.js +15 -2
  21. package/__tests__/shopping-adapters.test.js +96 -0
  22. package/__tests__/sign-providers.test.js +62 -0
  23. package/__tests__/travel-adapters.test.js +66 -0
  24. package/__tests__/whatsapp-adapter.test.js +5 -2
  25. package/lib/adapters/browser-history-chrome/chrome-db-reader.js +11 -1
  26. package/lib/adapters/email-imap/email-adapter.js +224 -17
  27. package/lib/adapters/messaging-telegram/index.js +15 -12
  28. package/lib/adapters/messaging-whatsapp/index.js +15 -12
  29. package/lib/adapters/shopping-taobao/index.js +161 -21
  30. package/lib/adapters/social-bilibili-adb/api-client.js +555 -0
  31. package/lib/adapters/social-bilibili-adb/chromium-cookies-reader.js +296 -0
  32. package/lib/adapters/social-bilibili-adb/collector.js +190 -0
  33. package/lib/adapters/social-bilibili-adb/cookies-extension.js +250 -0
  34. package/lib/adapters/social-bilibili-adb/index.js +51 -0
  35. package/lib/adapters/social-bilibili-adb/snapshot-builder.js +197 -0
  36. package/lib/adapters/social-douyin/index.js +4 -0
  37. package/lib/adapters/social-douyin-adb/collector.js +165 -0
  38. package/lib/adapters/social-douyin-adb/db-extension.js +281 -0
  39. package/lib/adapters/social-douyin-adb/im-db-parser.js +287 -0
  40. package/lib/adapters/social-douyin-adb/index.js +57 -0
  41. package/lib/adapters/social-douyin-adb/snapshot-builder.js +174 -0
  42. package/lib/adapters/social-weibo-adb/api-client.js +281 -0
  43. package/lib/adapters/social-weibo-adb/collector.js +169 -0
  44. package/lib/adapters/social-weibo-adb/cookies-extension.js +251 -0
  45. package/lib/adapters/social-weibo-adb/index.js +55 -0
  46. package/lib/adapters/social-weibo-adb/snapshot-builder.js +145 -0
  47. package/lib/adapters/social-xiaohongshu-adb/api-client.js +278 -0
  48. package/lib/adapters/social-xiaohongshu-adb/collector.js +158 -0
  49. package/lib/adapters/social-xiaohongshu-adb/cookies-extension.js +211 -0
  50. package/lib/adapters/social-xiaohongshu-adb/index.js +50 -0
  51. package/lib/adapters/social-xiaohongshu-adb/sign.js +90 -0
  52. package/lib/adapters/social-xiaohongshu-adb/snapshot-builder.js +126 -0
  53. package/lib/adapters/system-data-android/adapter.js +77 -3
  54. package/lib/adapters/travel-amap/index.js +16 -10
  55. package/lib/adapters/travel-ctrip/index.js +25 -9
  56. package/lib/adapters/vscode/vscode-reader.js +7 -1
  57. package/lib/sign-providers/index.js +20 -0
  58. package/lib/sign-providers/interface.js +82 -0
  59. package/lib/sign-providers/null-sign-provider.js +30 -0
  60. package/package.json +6 -1
@@ -0,0 +1,343 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Phase 1a (Bilibili C 路径) — unit cover for the bilibili.cookies ADB
5
+ * extension factory.
6
+ *
7
+ * Strategy: build a real chromium-shape Cookies sqlite via better-sqlite3,
8
+ * read it back as bytes, base64-encode, and feed the encoded string back
9
+ * to the extension via a fake `ctx.adb` that returns canned ADB stdout
10
+ * per-command. This exercises the full pipeline (probe → su id-u check →
11
+ * base64 stream → decode → sqlite magic check → parse → header assemble →
12
+ * temp-file cleanup) without any real ADB / device.
13
+ *
14
+ * Covered:
15
+ * - Happy path: pulls + parses + returns {cookie, uid, ...}
16
+ * - File not found on phone → BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN
17
+ * - Phone not rooted (id -u returns non-zero/non-root) → BILIBILI_NO_ROOT
18
+ * - Empty base64 stream → BILIBILI_COOKIES_EMPTY
19
+ * - Truncated stream (decoded <1KB) → BILIBILI_COOKIES_TRUNCATED
20
+ * - Wrong magic header (not sqlite) → BILIBILI_NOT_SQLITE
21
+ * - Cookies DB present but missing required cookies → BILIBILI_COOKIES_INCOMPLETE
22
+ * - Invalid DedeUserID (non-integer / negative) → BILIBILI_INVALID_UID
23
+ * - Cleanup: temp file deleted on both success and failure
24
+ * - Bridge integration via createHostAdbBridge({ extensions: {...} })
25
+ */
26
+
27
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
28
+ import {
29
+ mkdtempSync,
30
+ rmSync,
31
+ readFileSync,
32
+ writeFileSync,
33
+ existsSync,
34
+ readdirSync,
35
+ } from "node:fs";
36
+ import { join } from "node:path";
37
+ import { tmpdir } from "node:os";
38
+ import Database from "better-sqlite3";
39
+
40
+ const {
41
+ createBilibiliCookiesExtension,
42
+ BILIBILI_COOKIES_REMOTE_PATH,
43
+ } = require("../../lib/adapters/social-bilibili-adb/cookies-extension");
44
+
45
+ let tmpDir;
46
+
47
+ beforeEach(() => {
48
+ tmpDir = mkdtempSync(join(tmpdir(), "cc-bilibili-ext-test-"));
49
+ });
50
+
51
+ afterEach(() => {
52
+ try {
53
+ rmSync(tmpDir, { recursive: true, force: true });
54
+ } catch (_e) {
55
+ // ignore
56
+ }
57
+ });
58
+
59
+ /**
60
+ * Build a chromium-shape Cookies sqlite + return its raw bytes + base64.
61
+ * cookies = array of {name, value, hostKey?}.
62
+ */
63
+ function buildCookiesAsBase64(cookies) {
64
+ const dbPath = join(tmpDir, "fixture-cookies");
65
+ const db = new Database(dbPath);
66
+ db.exec(`
67
+ CREATE TABLE cookies(
68
+ creation_utc INTEGER,
69
+ host_key TEXT,
70
+ name TEXT,
71
+ value TEXT,
72
+ encrypted_value BLOB,
73
+ path TEXT,
74
+ expires_utc INTEGER,
75
+ is_secure INTEGER,
76
+ is_httponly INTEGER,
77
+ is_persistent INTEGER
78
+ );
79
+ `);
80
+ const insert = db.prepare(
81
+ "INSERT INTO cookies(host_key, name, value, path, expires_utc, is_secure, is_httponly, is_persistent) VALUES(?, ?, ?, '/', 0, 0, 1, 1)",
82
+ );
83
+ for (const c of cookies) {
84
+ insert.run(c.hostKey || ".bilibili.com", c.name, c.value);
85
+ }
86
+ db.close();
87
+ const buf = readFileSync(dbPath);
88
+ rmSync(dbPath);
89
+ return buf.toString("base64");
90
+ }
91
+
92
+ /**
93
+ * Build a fake ctx with a scripted adb response. `responses` is a Map
94
+ * keyed by the joined args (whitespace-stripped) → string stdout.
95
+ *
96
+ * `pickDevice` returns a fixed serial. `parseContentQueryRows` isn't
97
+ * used by the bilibili extension but is part of the ctx contract.
98
+ */
99
+ function fakeCtx(responses) {
100
+ return {
101
+ adb: vi.fn(async (args, _opts) => {
102
+ const key = args.join(" ");
103
+ // Allow exact key OR keyword-contains match (the extension only
104
+ // checks substrings; the test can opt into "first arg matching ..."
105
+ // by registering with a unique substring).
106
+ for (const [pattern, body] of responses) {
107
+ if (key === pattern || key.includes(pattern)) {
108
+ return typeof body === "function" ? body(args) : body;
109
+ }
110
+ }
111
+ throw new Error(`fake adb: no scripted response for: ${key}`);
112
+ }),
113
+ pickDevice: vi.fn(async () => "FAKE_SERIAL"),
114
+ parseContentQueryRows: () => [],
115
+ };
116
+ }
117
+
118
+ const FULL_BILIBILI_COOKIES = [
119
+ { name: "SESSDATA", value: "abcSESSDATA123" },
120
+ { name: "bili_jct", value: "csrfTokenXYZ" },
121
+ { name: "DedeUserID", value: "1234567890" },
122
+ { name: "DedeUserID__ckMd5", value: "deadbeef0000" },
123
+ { name: "buvid3", value: "buvid-uniq-id" },
124
+ ];
125
+
126
+ describe("bilibili.cookies extension — happy path", () => {
127
+ it("pulls + parses + returns {cookie, uid, ...}", async () => {
128
+ const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
129
+ const ctx = fakeCtx([
130
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH + "\n"],
131
+ ["id -u", "0\n"],
132
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
133
+ ]);
134
+ const ext = createBilibiliCookiesExtension();
135
+ const result = await ext({}, ctx);
136
+
137
+ expect(result.cookie).toContain("SESSDATA=abcSESSDATA123");
138
+ expect(result.cookie).toContain("bili_jct=csrfTokenXYZ");
139
+ expect(result.cookie).toContain("DedeUserID=1234567890");
140
+ expect(result.cookie).toContain("buvid3=buvid-uniq-id");
141
+ expect(result.uid).toBe(1234567890);
142
+ expect(result.extractedAt).toBeGreaterThan(0);
143
+ expect(result.diagnostic.cookieCount).toBe(5);
144
+ expect(result.diagnostic.hadEncrypted).toBe(false);
145
+ });
146
+
147
+ it("uid is parsed as positive integer", async () => {
148
+ const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
149
+ const ctx = fakeCtx([
150
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
151
+ ["id -u", "uid=0(root) gid=0(root)\n"], // alternate id -u format
152
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
153
+ ]);
154
+ const ext = createBilibiliCookiesExtension();
155
+ const result = await ext({}, ctx);
156
+ expect(Number.isInteger(result.uid)).toBe(true);
157
+ expect(result.uid).toBeGreaterThan(0);
158
+ });
159
+ });
160
+
161
+ describe("bilibili.cookies extension — failure modes", () => {
162
+ it("BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN when ls returns NOT_FOUND", async () => {
163
+ const ctx = fakeCtx([[`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, "NOT_FOUND\n"]]);
164
+ const ext = createBilibiliCookiesExtension();
165
+ await expect(ext({}, ctx)).rejects.toThrow(
166
+ /BILIBILI_NOT_INSTALLED_OR_NEVER_LOGGED_IN/,
167
+ );
168
+ });
169
+
170
+ it("BILIBILI_NO_ROOT when id -u not 0", async () => {
171
+ const ctx = fakeCtx([
172
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
173
+ ["id -u", "2000\n"], // shell user, not root
174
+ ]);
175
+ const ext = createBilibiliCookiesExtension();
176
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_NO_ROOT/);
177
+ });
178
+
179
+ it("BILIBILI_COOKIES_EMPTY when base64 stream is empty", async () => {
180
+ const ctx = fakeCtx([
181
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
182
+ ["id -u", "0\n"],
183
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, " \r\n"],
184
+ ]);
185
+ const ext = createBilibiliCookiesExtension();
186
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_EMPTY/);
187
+ });
188
+
189
+ it("BILIBILI_COOKIES_TRUNCATED when decoded file too small", async () => {
190
+ // 50 bytes of base64 → ~37 bytes decoded, way below 1KB threshold
191
+ const tinyB64 = Buffer.from("a".repeat(100)).toString("base64");
192
+ const ctx = fakeCtx([
193
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
194
+ ["id -u", "0\n"],
195
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, tinyB64],
196
+ ]);
197
+ const ext = createBilibiliCookiesExtension();
198
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_TRUNCATED/);
199
+ });
200
+
201
+ it("BILIBILI_NOT_SQLITE when magic header missing", async () => {
202
+ // 2KB of non-sqlite garbage
203
+ const garbage = Buffer.alloc(2048, "X").toString("base64");
204
+ const ctx = fakeCtx([
205
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
206
+ ["id -u", "0\n"],
207
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, garbage],
208
+ ]);
209
+ const ext = createBilibiliCookiesExtension();
210
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_NOT_SQLITE/);
211
+ });
212
+
213
+ it("BILIBILI_COOKIES_INCOMPLETE when required cookies missing", async () => {
214
+ const b64 = buildCookiesAsBase64([
215
+ { name: "SESSDATA", value: "abc" },
216
+ { name: "bili_jct", value: "csrf" },
217
+ // missing DedeUserID + DedeUserID__ckMd5 + buvid3
218
+ ]);
219
+ const ctx = fakeCtx([
220
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
221
+ ["id -u", "0\n"],
222
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
223
+ ]);
224
+ const ext = createBilibiliCookiesExtension();
225
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_COOKIES_INCOMPLETE/);
226
+ });
227
+
228
+ it("BILIBILI_INVALID_UID when DedeUserID is non-numeric", async () => {
229
+ const b64 = buildCookiesAsBase64([
230
+ { name: "SESSDATA", value: "abc" },
231
+ { name: "bili_jct", value: "csrf" },
232
+ { name: "DedeUserID", value: "not-a-number" },
233
+ { name: "DedeUserID__ckMd5", value: "deadbeef" },
234
+ { name: "buvid3", value: "x" },
235
+ ]);
236
+ const ctx = fakeCtx([
237
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
238
+ ["id -u", "0\n"],
239
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
240
+ ]);
241
+ const ext = createBilibiliCookiesExtension();
242
+ await expect(ext({}, ctx)).rejects.toThrow(/BILIBILI_INVALID_UID/);
243
+ });
244
+ });
245
+
246
+ describe("bilibili.cookies extension — temp file cleanup", () => {
247
+ function countTempFiles() {
248
+ // Count cc-bilibili-cookies-*.db files in os.tmpdir() at the time
249
+ // of inspection. We snapshot before/after to compare delta.
250
+ try {
251
+ return readdirSync(tmpdir()).filter((n) =>
252
+ n.startsWith("cc-bilibili-cookies-"),
253
+ ).length;
254
+ } catch (_e) {
255
+ return 0;
256
+ }
257
+ }
258
+
259
+ it("removes temp file on success", async () => {
260
+ const before = countTempFiles();
261
+ const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
262
+ const ctx = fakeCtx([
263
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
264
+ ["id -u", "0\n"],
265
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
266
+ ]);
267
+ const ext = createBilibiliCookiesExtension();
268
+ await ext({}, ctx);
269
+ const after = countTempFiles();
270
+ expect(after).toBe(before);
271
+ });
272
+
273
+ it("removes temp file on parse failure", async () => {
274
+ const before = countTempFiles();
275
+ const b64 = buildCookiesAsBase64([
276
+ { name: "SESSDATA", value: "abc" }, // incomplete → throws
277
+ ]);
278
+ const ctx = fakeCtx([
279
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
280
+ ["id -u", "0\n"],
281
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
282
+ ]);
283
+ const ext = createBilibiliCookiesExtension();
284
+ await expect(ext({}, ctx)).rejects.toThrow();
285
+ const after = countTempFiles();
286
+ expect(after).toBe(before); // cleanup still ran via try/finally
287
+ });
288
+ });
289
+
290
+ describe("bilibili.cookies extension — ctx contract", () => {
291
+ it("throws TypeError when ctx missing adb fn", async () => {
292
+ const ext = createBilibiliCookiesExtension();
293
+ await expect(
294
+ ext({}, { pickDevice: async () => "x" }),
295
+ ).rejects.toThrow(TypeError);
296
+ });
297
+
298
+ it("throws TypeError when ctx missing pickDevice fn", async () => {
299
+ const ext = createBilibiliCookiesExtension();
300
+ await expect(
301
+ ext({}, { adb: async () => "" }),
302
+ ).rejects.toThrow(TypeError);
303
+ });
304
+ });
305
+
306
+ describe("bilibili.cookies extension — bridge integration", () => {
307
+ it("works through createHostAdbBridge plugin point", async () => {
308
+ // Use createHostAdbBridge to verify the extension actually dispatches
309
+ // via the host-adb-bridge plugin pipeline (Phase B0 contract).
310
+ const { createHostAdbBridge } = await import(
311
+ "../../../cli/src/lib/host-adb-bridge.js"
312
+ );
313
+ const b64 = buildCookiesAsBase64(FULL_BILIBILI_COOKIES);
314
+
315
+ // The real createHostAdbBridge uses its own internal adb fn (calls
316
+ // real `execFile`), which would fail on CI without a device. To
317
+ // smoke-test the dispatch wiring we construct an extension that
318
+ // ignores ctx and returns the same shape directly — that proves
319
+ // the bridge invokes our handler.
320
+ const ext = createBilibiliCookiesExtension();
321
+
322
+ // Replace the ctx that the real bridge would build by giving the
323
+ // extension a wrapper that swaps in our fake ctx.
324
+ const wrappedExt = (params, _realCtx) => ext(params, fakeCtxClosure());
325
+
326
+ function fakeCtxClosure() {
327
+ return fakeCtx([
328
+ [`ls ${BILIBILI_COOKIES_REMOTE_PATH}`, BILIBILI_COOKIES_REMOTE_PATH],
329
+ ["id -u", "0\n"],
330
+ [`base64 ${BILIBILI_COOKIES_REMOTE_PATH}`, b64],
331
+ ]);
332
+ }
333
+
334
+ const bridge = createHostAdbBridge({
335
+ extensions: { "bilibili.cookies": wrappedExt },
336
+ });
337
+
338
+ expect(bridge.extensionMethods()).toContain("bilibili.cookies");
339
+ const result = await bridge.invoke("bilibili.cookies");
340
+ expect(result.uid).toBe(1234567890);
341
+ expect(result.cookie).toContain("SESSDATA=");
342
+ });
343
+ });
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * Phase 1b — unit cover for snapshot-builder (API responses → snapshot JSON).
5
+ *
6
+ * What we cover:
7
+ * - schemaVersion + snapshottedAt + account shape match adapter.js
8
+ * snapshot mode contract
9
+ * - 4 kinds (history/favourite/dynamic/follow) all populate correct fields
10
+ * - capturedAt comes from the kind-specific field (viewAt / savedAt /
11
+ * publishedAt / followedAt)
12
+ * - id derivation: stable for items with bvid/rid/mid, fallback to index
13
+ * - displayName defaults to empty string when omitted
14
+ * - Edge cases: empty arrays / null items / missing fields don't crash
15
+ * - writeSnapshotJson / cleanupSnapshotJson disk lifecycle
16
+ */
17
+
18
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
19
+ import { existsSync, readFileSync, mkdtempSync, rmSync } from "node:fs";
20
+ import { join } from "node:path";
21
+ import { tmpdir } from "node:os";
22
+
23
+ const {
24
+ buildSnapshot,
25
+ writeSnapshotJson,
26
+ cleanupSnapshotJson,
27
+ SNAPSHOT_SCHEMA_VERSION,
28
+ } = require("../../lib/adapters/social-bilibili-adb/snapshot-builder");
29
+
30
+ let tmpDir;
31
+
32
+ beforeEach(() => {
33
+ tmpDir = mkdtempSync(join(tmpdir(), "cc-snapshot-test-"));
34
+ });
35
+
36
+ afterEach(() => {
37
+ try {
38
+ rmSync(tmpDir, { recursive: true, force: true });
39
+ } catch (_e) {
40
+ // ignore
41
+ }
42
+ });
43
+
44
+ // ─── buildSnapshot ──────────────────────────────────────────────────────
45
+
46
+ describe("buildSnapshot — schema contract", () => {
47
+ it("returns the documented schema shape", () => {
48
+ const snap = buildSnapshot({
49
+ uid: 12345,
50
+ displayName: "alice",
51
+ history: [],
52
+ favourites: [],
53
+ dynamics: [],
54
+ follows: [],
55
+ snapshottedAt: 1716383021000,
56
+ });
57
+ expect(snap.schemaVersion).toBe(SNAPSHOT_SCHEMA_VERSION);
58
+ expect(snap.schemaVersion).toBe(1);
59
+ expect(snap.snapshottedAt).toBe(1716383021000);
60
+ expect(snap.account).toEqual({ uid: "12345", displayName: "alice" });
61
+ expect(Array.isArray(snap.events)).toBe(true);
62
+ });
63
+
64
+ it("converts uid to string in account", () => {
65
+ const snap = buildSnapshot({ uid: 42 });
66
+ expect(snap.account.uid).toBe("42");
67
+ expect(typeof snap.account.uid).toBe("string");
68
+ });
69
+
70
+ it("defaults displayName to empty string", () => {
71
+ const snap = buildSnapshot({ uid: 1 });
72
+ expect(snap.account.displayName).toBe("");
73
+ });
74
+
75
+ it("defaults snapshottedAt to Date.now() when omitted", () => {
76
+ const before = Date.now();
77
+ const snap = buildSnapshot({ uid: 1 });
78
+ const after = Date.now();
79
+ expect(snap.snapshottedAt).toBeGreaterThanOrEqual(before);
80
+ expect(snap.snapshottedAt).toBeLessThanOrEqual(after);
81
+ });
82
+
83
+ it("rejects non-positive uid", () => {
84
+ expect(() => buildSnapshot({ uid: 0 })).toThrow(TypeError);
85
+ expect(() => buildSnapshot({ uid: -1 })).toThrow(TypeError);
86
+ expect(() => buildSnapshot({ uid: "string" })).toThrow(TypeError);
87
+ });
88
+
89
+ it("rejects null / non-object input", () => {
90
+ expect(() => buildSnapshot(null)).toThrow(TypeError);
91
+ expect(() => buildSnapshot("string")).toThrow(TypeError);
92
+ });
93
+ });
94
+
95
+ describe("buildSnapshot — events", () => {
96
+ it("maps history items → kind=history events", () => {
97
+ const snap = buildSnapshot({
98
+ uid: 1,
99
+ history: [
100
+ {
101
+ bvid: "BV1xx",
102
+ avid: 100,
103
+ title: "Test",
104
+ viewAt: 1716383021,
105
+ duration: 300,
106
+ uploader: "u1",
107
+ uploaderMid: 999,
108
+ part: "Part1",
109
+ },
110
+ ],
111
+ });
112
+ expect(snap.events).toHaveLength(1);
113
+ expect(snap.events[0]).toMatchObject({
114
+ kind: "history",
115
+ id: "BV1xx",
116
+ capturedAt: 1716383021,
117
+ title: "Test",
118
+ bvid: "BV1xx",
119
+ avid: 100,
120
+ duration: 300,
121
+ uploader: "u1",
122
+ uploaderMid: 999,
123
+ part: "Part1",
124
+ });
125
+ });
126
+
127
+ it("maps favourite items → kind=favourite + id prefix", () => {
128
+ const snap = buildSnapshot({
129
+ uid: 1,
130
+ favourites: [
131
+ {
132
+ bvid: "BVfav1",
133
+ title: "F1",
134
+ savedAt: 1716383021000,
135
+ folderName: "MyFolder",
136
+ uploader: "u1",
137
+ },
138
+ ],
139
+ });
140
+ expect(snap.events[0].kind).toBe("favourite");
141
+ expect(snap.events[0].id).toBe("fav-BVfav1");
142
+ expect(snap.events[0].capturedAt).toBe(1716383021000);
143
+ expect(snap.events[0].folderName).toBe("MyFolder");
144
+ });
145
+
146
+ it("maps dynamic items → kind=dynamic + id prefix", () => {
147
+ const snap = buildSnapshot({
148
+ uid: 1,
149
+ dynamics: [
150
+ {
151
+ rid: "dyn-rid-1",
152
+ summary: "hi",
153
+ dynamicType: "av",
154
+ publishedAt: 1716383021000,
155
+ authorMid: 999,
156
+ authorName: "x",
157
+ },
158
+ ],
159
+ });
160
+ expect(snap.events[0].kind).toBe("dynamic");
161
+ expect(snap.events[0].id).toBe("dyn-dyn-rid-1");
162
+ expect(snap.events[0].capturedAt).toBe(1716383021000);
163
+ expect(snap.events[0].dynamicType).toBe("av");
164
+ });
165
+
166
+ it("maps follow items → kind=follow + id prefix + mid as string", () => {
167
+ const snap = buildSnapshot({
168
+ uid: 1,
169
+ follows: [
170
+ {
171
+ mid: 42,
172
+ uname: "Friend",
173
+ face: "https://x.png",
174
+ sign: "hi",
175
+ followedAt: 1716383021000,
176
+ },
177
+ ],
178
+ });
179
+ expect(snap.events[0].kind).toBe("follow");
180
+ expect(snap.events[0].id).toBe("follow-42");
181
+ expect(snap.events[0].mid).toBe("42");
182
+ expect(typeof snap.events[0].mid).toBe("string");
183
+ });
184
+
185
+ it("preserves event order: history → favourite → dynamic → follow", () => {
186
+ const snap = buildSnapshot({
187
+ uid: 1,
188
+ history: [{ bvid: "BV1", title: "h", viewAt: 1 }],
189
+ favourites: [{ bvid: "BV2", title: "f", savedAt: 2 }],
190
+ dynamics: [{ rid: "r1", summary: "d", dynamicType: "av", publishedAt: 3 }],
191
+ follows: [{ mid: 1, uname: "x", followedAt: 4 }],
192
+ });
193
+ const kinds = snap.events.map((e) => e.kind);
194
+ expect(kinds).toEqual(["history", "favourite", "dynamic", "follow"]);
195
+ });
196
+
197
+ it("uses snapshottedAt as fallback when capturedAt source is missing", () => {
198
+ const snap = buildSnapshot({
199
+ uid: 1,
200
+ snapshottedAt: 999,
201
+ history: [{ bvid: "BV1", title: "h" /* no viewAt */ }],
202
+ });
203
+ expect(snap.events[0].capturedAt).toBe(999);
204
+ });
205
+
206
+ it("uses index-based fallback id when key field missing", () => {
207
+ const snap = buildSnapshot({
208
+ uid: 1,
209
+ history: [{ title: "no bvid", viewAt: 1 }],
210
+ favourites: [{ title: "no bvid", savedAt: 1 }],
211
+ dynamics: [{ summary: "no rid", dynamicType: "av", publishedAt: 1 }],
212
+ follows: [{ uname: "no mid", followedAt: 1 }],
213
+ });
214
+ const ids = snap.events.map((e) => e.id);
215
+ expect(ids).toEqual(["history-0", "fav-0", "dyn-0", "follow-0"]);
216
+ });
217
+
218
+ it("skips null / non-object items", () => {
219
+ const snap = buildSnapshot({
220
+ uid: 1,
221
+ history: [null, { bvid: "BV1", title: "ok", viewAt: 1 }, undefined, "not an object"],
222
+ });
223
+ expect(snap.events).toHaveLength(1);
224
+ expect(snap.events[0].id).toBe("BV1");
225
+ });
226
+
227
+ it("handles empty / missing arrays", () => {
228
+ const snap = buildSnapshot({ uid: 1 });
229
+ expect(snap.events).toEqual([]);
230
+ });
231
+
232
+ it("handles non-array input fields gracefully", () => {
233
+ const snap = buildSnapshot({
234
+ uid: 1,
235
+ history: "not an array",
236
+ favourites: null,
237
+ dynamics: 42,
238
+ follows: { x: 1 },
239
+ });
240
+ expect(snap.events).toEqual([]);
241
+ });
242
+ });
243
+
244
+ // ─── writeSnapshotJson / cleanupSnapshotJson ────────────────────────────
245
+
246
+ describe("writeSnapshotJson + cleanupSnapshotJson", () => {
247
+ it("writes JSON to default tmpdir path", () => {
248
+ const snap = buildSnapshot({ uid: 1 });
249
+ const filePath = writeSnapshotJson(snap);
250
+ expect(existsSync(filePath)).toBe(true);
251
+ expect(filePath).toContain("cc-bilibili-snapshot-");
252
+ expect(filePath).toMatch(/\.json$/);
253
+ const parsed = JSON.parse(readFileSync(filePath, "utf-8"));
254
+ expect(parsed.schemaVersion).toBe(1);
255
+ cleanupSnapshotJson(filePath);
256
+ expect(existsSync(filePath)).toBe(false);
257
+ });
258
+
259
+ it("respects custom dir", () => {
260
+ const snap = buildSnapshot({ uid: 1 });
261
+ const filePath = writeSnapshotJson(snap, { dir: tmpDir });
262
+ expect(filePath.startsWith(tmpDir)).toBe(true);
263
+ expect(existsSync(filePath)).toBe(true);
264
+ });
265
+
266
+ it("respects custom fileName", () => {
267
+ const snap = buildSnapshot({ uid: 1 });
268
+ const filePath = writeSnapshotJson(snap, {
269
+ dir: tmpDir,
270
+ fileName: "custom.json",
271
+ });
272
+ expect(filePath).toBe(join(tmpDir, "custom.json"));
273
+ });
274
+
275
+ it("rejects fileName with path separators", () => {
276
+ const snap = buildSnapshot({ uid: 1 });
277
+ expect(() =>
278
+ writeSnapshotJson(snap, { dir: tmpDir, fileName: "../escape.json" }),
279
+ ).toThrow(/must be a basename/);
280
+ expect(() =>
281
+ writeSnapshotJson(snap, { dir: tmpDir, fileName: "sub/path.json" }),
282
+ ).toThrow(/must be a basename/);
283
+ });
284
+
285
+ it("cleanupSnapshotJson is no-op on missing file", () => {
286
+ cleanupSnapshotJson(join(tmpDir, "nonexistent.json"));
287
+ // Should not throw
288
+ });
289
+
290
+ it("cleanupSnapshotJson tolerates null / empty", () => {
291
+ cleanupSnapshotJson(null);
292
+ cleanupSnapshotJson("");
293
+ cleanupSnapshotJson(undefined);
294
+ // Should not throw
295
+ });
296
+ });