dsh-palace 1.3.1 → 1.3.2

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.
package/lib/index.js CHANGED
@@ -72,9 +72,14 @@ function periodOf(item) {
72
72
  function monthOf(iso) {
73
73
  return /^\d{4}-\d{2}-\d{2}$/.test(iso) ? iso.slice(0, 7) : today(new Date(iso)).slice(0, 7);
74
74
  }
75
+ function weReadPosition(item) {
76
+ const { position } = item;
77
+ return item.source === null && position && (position.loc === "" || position.loc.startsWith("weread:")) ? position : void 0;
78
+ }
75
79
  function percentOf(item, done, total) {
76
80
  if (item.finishedAt !== void 0) return 1;
77
- if (item.source?.type === "epub" && item.position !== void 0) return item.position.percent;
81
+ const position = item.source?.type === "epub" ? item.position : weReadPosition(item);
82
+ if (position) return position.percent;
78
83
  return total > 0 ? done / total : void 0;
79
84
  }
80
85
  function findSection(item, sectionId) {
@@ -1411,9 +1416,10 @@ var responseList = {
1411
1416
  "/user/notebooks": "books",
1412
1417
  "/review/list/mine": "reviews",
1413
1418
  "/book/chapterinfo": "chapters",
1414
- "/book/bookmarklist": "updated"
1419
+ "/book/bookmarklist": "updated",
1420
+ "/book/getprogress": "book"
1415
1421
  };
1416
- function outline(chapters, cards) {
1422
+ function outline(chapters, cards, chapterUid) {
1417
1423
  const result = [];
1418
1424
  for (const chapter of chapters) {
1419
1425
  const title = chapter.title?.trim();
@@ -1423,7 +1429,7 @@ function outline(chapters, cards) {
1423
1429
  if (level === 1 || level === 2 && !result.length) result.push(row);
1424
1430
  else if (level === 2) result.at(-1).sections.push({ title: row.title, loc: row.loc });
1425
1431
  }
1426
- const marked = new Set(cards.map((card) => card.sectionKey));
1432
+ const marked = /* @__PURE__ */ new Set([chapterUid, ...cards.map((card) => card.sectionKey)]);
1427
1433
  for (const row of result) {
1428
1434
  if (row.sections?.length && row.loc && marked.has(row.loc)) row.sections.unshift({ title: row.title, loc: row.loc });
1429
1435
  }
@@ -1464,7 +1470,8 @@ function createWeRead(fetcher = fetch, keyReader = readKey) {
1464
1470
  }
1465
1471
  if (code === 401 || code === 403) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u9274\u6743\u5931\u8D25\uFF0C\u8BF7\u66F4\u6362 API Key");
1466
1472
  if (!response.ok || !data || Number(data.errcode ?? 0) !== 0) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u63A5\u53E3\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
1467
- if (!Array.isArray(data[responseList[api_name]])) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u56DE\u5305\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u8BD5");
1473
+ const value = data[responseList[api_name]];
1474
+ if (api_name === "/book/getprogress" ? !value || typeof value !== "object" || Array.isArray(value) : !Array.isArray(value)) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u56DE\u5305\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u91CD\u8BD5");
1468
1475
  return data;
1469
1476
  } catch (error) {
1470
1477
  if (error instanceof ShelfError) throw error;
@@ -1497,21 +1504,25 @@ function createWeRead(fetcher = fetch, keyReader = readKey) {
1497
1504
  let listing;
1498
1505
  let prepared;
1499
1506
  return {
1500
- async scan(signal) {
1507
+ async scan(signal, imported = (_id) => false) {
1501
1508
  const key = currentKey();
1502
1509
  listing = { key, data: await shelf(key, signal) };
1503
1510
  prepared = void 0;
1504
1511
  const { books, total } = listing.data;
1505
1512
  return { total, withNotes: [...books.values()].filter((book) => book.hasNotes).length, books: [...books.values()].map(
1506
- ({ bookId, title, author, category, finishReading, readUpdateTime, publishTime, hasNotes }) => ({ bookId, title, author, category, finished: finishReading === 1, readUpdateTime, publishTime, hasNotes })
1513
+ ({ bookId, title, author, category, finishReading, readUpdateTime, publishTime, hasNotes }) => ({ bookId, title, author, category, finished: finishReading === 1, readUpdateTime, publishTime, hasNotes, imported: imported(bookId) })
1507
1514
  ) };
1508
1515
  },
1509
- async prepare(plan, confirming, signal) {
1510
- if (!Array.isArray(plan) || plan.length === 0 || plan.some((id) => typeof id !== "string" || !id)) throw new ShelfError("\u8BF7\u63D0\u4F9B\u8981\u5BFC\u5165\u7684 bookId \u5217\u8868");
1511
- const key = currentKey(), ids = [...new Set(plan)], fingerprint = JSON.stringify(ids);
1516
+ async prepare(plan, confirming, signal, imported) {
1517
+ if (plan !== void 0 && (!Array.isArray(plan) || plan.length === 0 || plan.some((id) => typeof id !== "string" || !id))) throw new ShelfError("\u8BF7\u63D0\u4F9B\u8981\u5BFC\u5165\u7684 bookId \u5217\u8868");
1518
+ const key = currentKey(), explicit = plan === void 0 ? void 0 : [...new Set(plan)];
1519
+ const fingerprint = JSON.stringify(explicit ?? null);
1512
1520
  if (confirming && prepared?.key === key && prepared.plan === fingerprint) return prepared.batch;
1513
1521
  if (confirming) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u9884\u89C8\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9884\u89C8\u5E76\u786E\u8BA4");
1514
1522
  const { books } = listing?.key === key ? listing.data : await shelf(key, signal);
1523
+ listing = void 0;
1524
+ const ids = explicit ?? [...books.keys()].filter(imported);
1525
+ if (!ids.length) throw new ShelfError("\u6CA1\u6709\u53EF\u540C\u6B65\u7684\u4E66\uFF0C\u8BF7\u5148\u9009\u4E66\u5BFC\u5165");
1515
1526
  const groups = [];
1516
1527
  for (const id of ids) {
1517
1528
  const book = books.get(id);
@@ -1519,6 +1530,11 @@ function createWeRead(fetcher = fetch, keyReader = readKey) {
1519
1530
  const href = [book.readerLink, book.deepLink].find((link) => typeof link === "string" && /^https?:\/\//.test(link));
1520
1531
  const group = { key: id, kind: "book", title: book.title, href, cards: [] };
1521
1532
  groups.push(group);
1533
+ const { book: { progress, finishTime, chapterUid } } = await request(key, "/book/getprogress", { bookId: id }, signal);
1534
+ if (typeof progress === "number" && Number.isInteger(progress) && progress >= 0 && progress <= 100) {
1535
+ const finish = progress === 100 && typeof finishTime === "number" && finishTime > 0 ? new Date(finishTime * 1e3) : void 0;
1536
+ group.progress = { percent: progress / 100, chapterUid: chapterUid?.toString(), finishedAt: finish && Number.isFinite(finish.getTime()) ? today(finish) : void 0 };
1537
+ }
1522
1538
  if (!book.hasNotes) continue;
1523
1539
  const reviews = async () => {
1524
1540
  const rows = [];
@@ -1557,7 +1573,7 @@ function createWeRead(fetcher = fetch, keyReader = readKey) {
1557
1573
  cards.set(key2, { key: key2, type: row.abstract?.trim() ? "excerpt" : "thought", quote: row.abstract || void 0, note: row.content, sectionKey: row.chapterUid?.toString() });
1558
1574
  }
1559
1575
  group.cards = [...cards.values()];
1560
- group.chapters = outline(toc.chapters, group.cards);
1576
+ group.chapters = outline(toc.chapters, group.cards, group.progress?.chapterUid);
1561
1577
  }
1562
1578
  const batch = { source: "weread", groups, links: [] };
1563
1579
  prepared = { key, plan: fingerprint, batch };
@@ -1840,7 +1856,7 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
1840
1856
  import { createHash } from "node:crypto";
1841
1857
  var digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1842
1858
  var stableId = (prefix, ...key) => `${prefix}_${digest(key).slice(0, 10)}`;
1843
- async function importBatch(store, memory, batch, confirmation, onlyNew = false) {
1859
+ async function importBatch(store, memory, batch, confirmation) {
1844
1860
  const palace = store.getPalace();
1845
1861
  const cells = new Map(palace.cells.map((cell) => [cell.id, cell]));
1846
1862
  const placed = /* @__PURE__ */ new Map();
@@ -1852,6 +1868,8 @@ async function importBatch(store, memory, batch, confirmation, onlyNew = false)
1852
1868
  }
1853
1869
  const newCells = /* @__PURE__ */ new Map();
1854
1870
  const outlines = /* @__PURE__ */ new Map();
1871
+ const progress = [];
1872
+ const progressWrites = /* @__PURE__ */ new Map();
1855
1873
  const selected = /* @__PURE__ */ new Map();
1856
1874
  const at = nowIso();
1857
1875
  for (const group of batch.groups) {
@@ -1862,14 +1880,27 @@ async function importBatch(store, memory, batch, confirmation, onlyNew = false)
1862
1880
  target = { id, kind: group.kind ?? "note", title: group.title, href: group.href, parentId: null, col: 0, row: 0, createdAt: at };
1863
1881
  newCells.set(id, target);
1864
1882
  }
1865
- if (target && group.chapters?.length && (newCells.has(id) || store.getItem(id).chapters.length === 0)) outlines.set(id, group.chapters);
1883
+ if (target && group.chapters?.length && (newCells.has(id) || store.getItem(id).chapters.length === 0)) outlines.set(id, buildChapters(group.chapters));
1884
+ if (target?.kind === "book" && group.progress) {
1885
+ const { percent, finishedAt, chapterUid } = group.progress;
1886
+ const item = newCells.has(id) ? void 0 : store.getItem(id);
1887
+ const sections = (outlines.get(id) ?? item?.chapters ?? []).flatMap((chapter) => chapter.sections);
1888
+ const current = chapterUid === void 0 ? -1 : sections.findIndex((section) => section.loc === chapterUid);
1889
+ const mark = sections.slice(0, Math.max(0, current)).flatMap((section, index) => section.done ? [] : [index]);
1890
+ const loc = current < 0 ? "" : "weread:" + chapterUid;
1891
+ progress.push({ bookId: group.key, title: target.title, percent: Math.round(percent * 100), finished: (finishedAt ?? item?.finishedAt) !== void 0, markRead: mark.length });
1892
+ if (mark.length || item?.position?.loc !== loc || item.position.percent !== percent || finishedAt !== void 0 && item.finishedAt !== finishedAt) {
1893
+ progressWrites.set(id, { percent, finishedAt, loc, mark });
1894
+ }
1895
+ }
1866
1896
  for (const input of group.cards) {
1867
1897
  if (selected.has(input.key)) throw new ShelfError(`\u65B9\u6848\u91CC\u91CD\u590D\u51FA\u73B0\uFF1A${input.key}`);
1868
1898
  const previous = placed.get(input.key);
1869
1899
  if (previous && group.itemId !== void 0 && previous.cell.id !== group.itemId) throw new ShelfError(`\u5DF2\u5BFC\u5165\u7684\u7B14\u8BB0\u7559\u5728\u539F\u683C\u5B50\uFF1A${input.key}`);
1870
1900
  const content = digest(input.type === void 0 ? [input.note, input.frontmatter] : [input.type, input.note, input.quote, input.sectionKey]);
1871
1901
  const card = {
1872
- ...previous?.card ?? { id: stableId("k", batch.source, input.key), type: input.type ?? "thought", quote: input.quote, createdAt: at },
1902
+ ...previous?.card ?? { id: stableId("k", batch.source, input.key), type: "thought", createdAt: at },
1903
+ ...input.type !== void 0 ? { type: input.type, quote: input.quote } : {},
1873
1904
  note: previous?.card.importSource?.digest === content ? previous.card.note : input.note,
1874
1905
  importSource: { source: batch.source, key: input.key, digest: content, frontmatter: input.frontmatter }
1875
1906
  };
@@ -1888,7 +1919,7 @@ async function importBatch(store, memory, batch, confirmation, onlyNew = false)
1888
1919
  const sourceKey = digest([batch.source, pair, occurrence, from.cell.id, to.cell.id]);
1889
1920
  links.push({ sourceKey, from: from.cell.id, to: to.cell.id, why: link.why, evidence: [from.card.id, to.card.id], fromPath: link.from, toPath: link.to });
1890
1921
  }
1891
- const changed = [...selected.values()].filter(({ previous, card }) => previous === void 0 || !onlyNew && previous.importSource?.digest !== card.importSource?.digest);
1922
+ const changed = [...selected.values()].filter(({ previous, card }) => previous?.importSource?.digest !== card.importSource?.digest);
1892
1923
  const { pending, arcs, strands } = memory.previewImportedLinks(
1893
1924
  links.map(({ sourceKey, from, to, why, evidence }) => ({ sourceKey, from, to, why, evidence }))
1894
1925
  );
@@ -1897,19 +1928,30 @@ async function importBatch(store, memory, batch, confirmation, onlyNew = false)
1897
1928
  cards: changed.filter((x) => !x.previous).length,
1898
1929
  updatedCards: changed.filter((x) => x.previous).length,
1899
1930
  arcs,
1900
- strands
1931
+ strands,
1932
+ ...progress.length ? { progress } : {}
1901
1933
  };
1902
- const token = digest([batch, [...selected].map(([key, x]) => [key, x.cell.id, x.previous?.id]), links, pending, [...outlines.keys()], summary]);
1934
+ const token = digest([batch, [...selected].map(([key, x]) => [key, x.cell.id, x.previous?.id]), links, pending, [...outlines.keys()], [...progressWrites], summary]);
1903
1935
  if (confirmation === void 0) return { preview: true, ...summary, token };
1904
1936
  if (confirmation !== token) throw new ShelfError("\u7B14\u8BB0\u3001\u65B9\u6848\u6216\u5BAB\u6BBF\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u9884\u89C8\u5E76\u786E\u8BA4");
1905
- if (changed.length || newCells.size || outlines.size) {
1937
+ if (changed.length || newCells.size || outlines.size || progressWrites.size) {
1906
1938
  await store.mutate((tx) => {
1907
1939
  for (const cell of newCells.values()) {
1908
1940
  Object.assign(cell, firstEmptySlot(tx.palace, null));
1909
1941
  tx.palace.cells.push(cell);
1910
1942
  tx.createItem(emptyItem(cell.id, null));
1911
1943
  }
1912
- for (const [id, chapters] of outlines) tx.item(id).chapters = buildChapters(chapters);
1944
+ for (const [id, chapters] of outlines) tx.item(id).chapters = chapters;
1945
+ for (const [id, { percent, finishedAt, loc, mark }] of progressWrites) {
1946
+ const item = tx.item(id);
1947
+ item.position = { loc, percent };
1948
+ if (finishedAt !== void 0) item.finishedAt = finishedAt;
1949
+ const sections = item.chapters.flatMap((chapter) => chapter.sections);
1950
+ for (const index of mark) {
1951
+ const section = sections[index];
1952
+ if (section && !section.done) Object.assign(section, { done: true, doneAt: at });
1953
+ }
1954
+ }
1913
1955
  for (const { cell, card, previous, sectionKey } of changed) {
1914
1956
  const item = tx.item(cell.id);
1915
1957
  if (sectionKey !== void 0) card.sectionId = item.chapters.flatMap((chapter) => chapter.sections).find((section) => section.loc === sectionKey)?.id;
@@ -1941,11 +1983,15 @@ function cellLine(store, c, active) {
1941
1983
  const pace = paceOf(item);
1942
1984
  const todo = item.cards.filter((k) => k.type === "mistake" && k.status === "todo").length;
1943
1985
  if (item.source !== null) line += ` \u539F\u6587 ${item.source.type}${item.source.type === "pdf" ? ` ${item.source.pageCount} \u9875` : ""}`;
1944
- if (p.total > 0) line += ` \u8FDB\u5EA6 ${p.done}/${p.total} \u8282`;
1986
+ const external = weReadPosition(item);
1987
+ if (external) {
1988
+ const chapter = item.chapters.findIndex((chapter2) => chapter2.sections.some((section) => "weread:" + section.loc === external.loc)) + 1;
1989
+ line += ` \u5DF2\u8BFB ${Math.round(external.percent * 100)}%${chapter ? `\uFF0C\u8BFB\u5230\u7B2C ${chapter} \u7AE0` : ""}\uFF08\u6765\u81EA\u5FAE\u4FE1\u8BFB\u4E66\uFF09`;
1990
+ } else if (p.total > 0) line += ` \u8FDB\u5EA6 ${p.done}/${p.total} \u8282`;
1945
1991
  else if (item.source?.type === "pdf") line += "\uFF08\u8FD8\u6CA1\u6709\u76EE\u5F55\uFF09";
1946
1992
  if (item.targetDate) line += ` \u76EE\u6807\u65E5\u671F ${item.targetDate}`;
1947
1993
  if (pace?.perDay !== void 0 && pace.remaining > 0) line += ` \u6BCF\u5929\u7EA6 ${pace.perDay} \u8282`;
1948
- if (p.current) line += ` \u5F53\u524D\uFF1A${p.current.chapter.title} \u203A ${p.current.section.title}`;
1994
+ if (!external && p.current) line += ` \u5F53\u524D\uFF1A${p.current.chapter.title} \u203A ${p.current.section.title}`;
1949
1995
  if (item.cards.length > 0) line += ` \u5361\u7247 ${item.cards.length} \u5F20${todo > 0 ? `\uFF08\u5F85\u91CD\u505A\u9519\u9898 ${todo}\uFF09` : ""}`;
1950
1996
  if (item.inspirations.length > 0) line += ` \u7075\u611F ${item.inspirations.length} \u6761`;
1951
1997
  }
@@ -2320,28 +2366,32 @@ function createObsidianTools(store, memory, source) {
2320
2366
  ];
2321
2367
  }
2322
2368
  function createWeReadTools(store, memory, source) {
2369
+ const importedBooks = () => {
2370
+ const ids = new Set(store.getPalace().cells.filter((cell) => cell.kind === "book").map((cell) => cell.id));
2371
+ return (bookId) => ids.has(stableId("c", "weread", bookId));
2372
+ };
2323
2373
  return [
2324
2374
  {
2325
2375
  name: "palace_scan_weread",
2326
- description: "\u9884\u89C8\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u67B6\u548C\u6709\u5212\u7EBF\u6216\u60F3\u6CD5\u7684\u4E66\u3002\u7528\u6237\u63D0\u51FA\u5BFC\u5165\u65F6\uFF0C\u5148\u7528\u8FD9\u4E9B\u4FE1\u606F\u5546\u91CF\u8981\u5BFC\u5165\u54EA\u4E9B\u4E66\u3002",
2376
+ description: "\u67E5\u770B\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u67B6\u53CA\u7B14\u8BB0\u3002\u540C\u6B65\u6216\u518D\u6B21\u4ECE\u5165\u53E3\u5BFC\u5165\u65F6\uFF0C\u9ED8\u8BA4\u9884\u89C8\u5DF2\u5BFC\u5165\u7684\u4E66\uFF1B\u6709\u7B14\u8BB0\u4F46\u672A\u5BFC\u5165\u7684\u4E66\u53EA\u63D0\u793A\uFF0C\u7528\u6237\u660E\u786E\u9009\u4E2D\u624D\u5BFC\u5165\u3002",
2327
2377
  parameters: {},
2328
2378
  async execute(_args, { signal }) {
2329
- return guard(async () => JSON.stringify(await source.scan(signal)));
2379
+ return guard(async () => JSON.stringify(await source.scan(signal, importedBooks())));
2330
2380
  }
2331
2381
  },
2332
2382
  {
2333
2383
  name: "palace_import_weread",
2334
- description: "\u628A\u9009\u4E2D\u7684\u5FAE\u4FE1\u8BFB\u4E66\u4E66\u548C\u7B14\u8BB0\u5BFC\u5165\u5BAB\u6BBF\u3002plan \u586B\u626B\u63CF\u5F97\u5230\u7684 bookId \u5217\u8868\u3002\u5148\u7701\u7565 confirmation \u8FDB\u884C\u9884\u89C8\uFF0C\u7B49\u7528\u6237\u786E\u8BA4\u540E\u7528\u540C\u4E00\u65B9\u6848\u548C\u9884\u89C8\u7684 token \u5199\u5165\u3002",
2384
+ description: "\u5BFC\u5165\u6216\u540C\u6B65\u5FAE\u4FE1\u8BFB\u4E66\u3002\u540C\u6B65\u5148\u626B\u63CF\uFF0C\u7701\u7565 plan \u9ED8\u8BA4\u540C\u6B65\u5DF2\u5BFC\u5165\u7684\u4E66\uFF1B\u660E\u786E\u9009\u4E66\u624D\u4F20 bookId \u5217\u8868\u3002\u5148\u7701\u7565 confirmation\uFF0C\u5411\u7528\u6237\u8BF4\u660E\u65B0\u589E\u3001\u66F4\u65B0\u7684\u5361\u7247\u6570\u3001\u9605\u8BFB\u767E\u5206\u6BD4\u548C\u5C06\u6807\u8BB0\u4E3A\u5DF2\u8BFB\u7684\u8282\u6570\uFF08markRead\uFF09\uFF1B\u7528\u6237\u786E\u8BA4\u540E\u7528\u540C\u4E00\u65B9\u6848\u548C\u9884\u89C8 token \u5199\u5165\u3002",
2335
2385
  parameters: {
2336
- plan: { type: "array", required: true, items: { type: "string" } },
2386
+ plan: { type: "array", items: { type: "string" } },
2337
2387
  confirmation: { type: "string" }
2338
2388
  },
2339
2389
  async execute({ plan, confirmation }, { signal }) {
2340
2390
  return guard(async () => {
2341
2391
  if (confirmation !== void 0 && typeof confirmation !== "string") throw new ShelfError("\u8BF7\u4F7F\u7528\u9884\u89C8\u8FD4\u56DE\u7684 token");
2342
- const batch = await source.prepare(plan, confirmation !== void 0, signal);
2392
+ const batch = await source.prepare(plan, confirmation !== void 0, signal, importedBooks());
2343
2393
  if (signal?.aborted) throw new ShelfError("\u5FAE\u4FE1\u8BFB\u4E66\u5BFC\u5165\u5DF2\u53D6\u6D88");
2344
- return JSON.stringify(await importBatch(store, memory, batch, confirmation, true));
2394
+ return JSON.stringify(await importBatch(store, memory, batch, confirmation));
2345
2395
  });
2346
2396
  }
2347
2397
  }