dsh-plugin-zotero 0.2.0 → 0.3.0

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.
@@ -99,18 +99,43 @@ async function handleItems(res, params) {
99
99
  }
100
100
  const collectionKey = params.get('collectionKey') ?? undefined;
101
101
  const q = params.get('q') ?? undefined;
102
+ const tags = params.getAll('tag').map((tag) => tag.trim()).filter((tag) => tag !== '');
103
+ const tagMode = params.get('tagMode') === 'any' ? 'any' : 'all';
102
104
  const limit = clampLimit(params.get('limit'));
103
105
  const offset = parseOffset(params.get('offset'));
104
106
  const result = await zotero.listItems({
105
107
  scope: scopeParam === null ? undefined : scopeParam,
106
108
  collectionKey,
107
109
  q,
110
+ tags,
111
+ tagMode,
108
112
  limit,
109
113
  offset,
110
114
  });
111
115
  const data = { total: result.total, items: result.items };
112
116
  ok(res, data);
113
117
  }
118
+ async function handleTags(res) {
119
+ const data = await zotero.listTags();
120
+ ok(res, data);
121
+ }
122
+ /** 当前范围内的标签用量(供标签面板列出范围标签)。 */
123
+ async function handleTagUsage(res, params) {
124
+ const scopeParam = params.get('scope');
125
+ if (scopeParam !== null && !isScope(scopeParam)) {
126
+ fail(res, 400, 'bad_request', `未知 scope ${scopeParam}`);
127
+ return;
128
+ }
129
+ const collectionKeys = params.getAll('collectionKey')
130
+ .map((key) => key.trim())
131
+ .filter((key) => key !== '');
132
+ const data = await zotero.listTagUsage({
133
+ scope: scopeParam === null ? undefined : scopeParam,
134
+ collectionKeys: collectionKeys.length === 0 ? undefined : collectionKeys,
135
+ q: params.get('q') ?? undefined,
136
+ });
137
+ ok(res, data);
138
+ }
114
139
  async function handleItem(res, params) {
115
140
  const key = params.get('key');
116
141
  if (!key) {
@@ -159,6 +184,12 @@ export function createHandler(deps = {}) {
159
184
  case 'items':
160
185
  await handleItems(res, url.searchParams);
161
186
  return;
187
+ case 'tags':
188
+ await handleTags(res);
189
+ return;
190
+ case 'tag-usage':
191
+ await handleTagUsage(res, url.searchParams);
192
+ return;
162
193
  case 'item':
163
194
  await handleItem(res, url.searchParams);
164
195
  return;
@@ -13,7 +13,7 @@
13
13
  * - `?include=bib` 会让响应**丢掉 `data`**,因此条目详情与 bib 必须分两次请求。
14
14
  */
15
15
  import { type RawAnnotation } from './annotations.js';
16
- import type { ApiErrorCode, ZoteroCollection, ZoteroFulltext, ZoteroHealth, ZoteroItemDetail, ZoteroItemScope, ZoteroItemSummary } from './types.js';
16
+ import type { ApiErrorCode, ZoteroCollection, ZoteroFulltext, ZoteroHealth, ZoteroItemDetail, ZoteroItemScope, ZoteroItemSummary, ZoteroTags } from './types.js';
17
17
  /** 归一化后的 Zotero 访问错误。 */
18
18
  export declare class ZoteroError extends Error {
19
19
  readonly code: ApiErrorCode;
@@ -27,6 +27,13 @@ interface RawCreator {
27
27
  }
28
28
  interface RawTag {
29
29
  tag?: string;
30
+ /** 条目 `data.tags` 上的类型(0 自动标签,1 手动标签);`/tags` 端点在 `meta.type`。 */
31
+ type?: number;
32
+ meta?: {
33
+ /** 0 自动标签,1 手动标签。 */
34
+ type?: number;
35
+ numItems?: number;
36
+ };
30
37
  }
31
38
  interface RawItemData {
32
39
  itemType?: string;
@@ -101,11 +108,43 @@ export declare function callMcpTool(name: string, args: unknown, signal?: AbortS
101
108
  export declare function getLibraryName(): Promise<string>;
102
109
  /** 全量分类(扁平,含 parentCollection 与 numItems)。 */
103
110
  export declare function listCollections(): Promise<ZoteroCollection[]>;
111
+ /**
112
+ * 文库级标签列表。
113
+ *
114
+ * 本地 API 没有「按分类的标签」端点(`/tags` 上的 `collectionKey` / `q` 实测被忽略),
115
+ * 所以计数是**全库**的;范围用量另走 {@link listTagUsage}。
116
+ * 按名称去重(同名标签只可能来自分页重复),`meta.type` / `numItems` 缺失时
117
+ * 分别按手动标签与 0 处理,避免 UI 出现 `NaN`。
118
+ */
119
+ export declare function listTags(): Promise<ZoteroTags>;
120
+ export interface ListTagUsageOptions {
121
+ /** 虚拟分类范围;缺省或 `library` 走真实分类/全库。 */
122
+ scope?: ZoteroItemScope;
123
+ /**
124
+ * 真实分类 key 列表(可含子目录);空/缺省 = 全库。
125
+ * 分类本身不含子分类条目,子树集合由调用方展开后传进来。
126
+ */
127
+ collectionKeys?: readonly string[];
128
+ /** 与条目列表同一个搜索词,标签可用性才跟列表口径一致。 */
129
+ q?: string;
130
+ }
131
+ /**
132
+ * 当前范围(分类 / 虚拟分类 + 搜索词)内的标签用量。
133
+ *
134
+ * 只能扫条目现算:逐页取范围内的顶层条目,读每条的 `data.tags` 累加计数。
135
+ * 传多个 `collectionKeys` 时分目录扫描,并按条目 key 去重——同一篇条目可能
136
+ * 同时挂在父分类与子分类里,不能重复计数。超过 `USAGE_SCAN_MAX` 条的大范围
137
+ * 按前若干页截断,超大目录可能漏掉靠后的标签(本地 API 没有按分类列标签的端点)。
138
+ */
139
+ export declare function listTagUsage(options: ListTagUsageOptions): Promise<ZoteroTags>;
104
140
  export interface ListItemsOptions {
105
141
  /** 虚拟分类范围;缺省或 `library` 走真实分类/全库。 */
106
142
  scope?: ZoteroItemScope;
107
143
  collectionKey?: string;
108
144
  q?: string;
145
+ /** 标签过滤:AND(默认)逐个 `tag=`,OR 合并成 `tag=A || B`。 */
146
+ tags?: readonly string[];
147
+ tagMode?: 'all' | 'any';
109
148
  limit: number;
110
149
  offset: number;
111
150
  }
@@ -339,6 +339,103 @@ export async function listCollections() {
339
339
  };
340
340
  });
341
341
  }
342
+ // ---- 标签 -------------------------------------------------------------------
343
+ /** 标签分页大小(本地 API 上限 1000)与总量上限。 */
344
+ const TAG_PAGE_SIZE = 1000;
345
+ const TAG_MAX = 5000;
346
+ /**
347
+ * 文库级标签列表。
348
+ *
349
+ * 本地 API 没有「按分类的标签」端点(`/tags` 上的 `collectionKey` / `q` 实测被忽略),
350
+ * 所以计数是**全库**的;范围用量另走 {@link listTagUsage}。
351
+ * 按名称去重(同名标签只可能来自分页重复),`meta.type` / `numItems` 缺失时
352
+ * 分别按手动标签与 0 处理,避免 UI 出现 `NaN`。
353
+ */
354
+ export async function listTags() {
355
+ const seen = new Map();
356
+ let total = 0;
357
+ for (let start = 0; start < TAG_MAX; start += TAG_PAGE_SIZE) {
358
+ const { body, total: pageTotal } = await requestJson(`${libraryBase()}/tags?limit=${TAG_PAGE_SIZE}&start=${start}`);
359
+ const page = Array.isArray(body) ? body : [];
360
+ if (pageTotal !== null)
361
+ total = pageTotal;
362
+ for (const raw of page) {
363
+ const name = raw.tag?.trim() ?? '';
364
+ if (name === '' || seen.has(name))
365
+ continue;
366
+ seen.set(name, {
367
+ name,
368
+ count: raw.meta?.numItems ?? 0,
369
+ type: raw.meta?.type ?? 1,
370
+ });
371
+ }
372
+ if (page.length < TAG_PAGE_SIZE)
373
+ break;
374
+ if (total > 0 && start + page.length >= total)
375
+ break;
376
+ }
377
+ return { total: total || seen.size, tags: [...seen.values()] };
378
+ }
379
+ /** 标签用量扫描的分页大小(本地 API 单页上限 100)与扫描条目上限。 */
380
+ const USAGE_PAGE_SIZE = 100;
381
+ const USAGE_SCAN_MAX = 3000;
382
+ /**
383
+ * 当前范围(分类 / 虚拟分类 + 搜索词)内的标签用量。
384
+ *
385
+ * 只能扫条目现算:逐页取范围内的顶层条目,读每条的 `data.tags` 累加计数。
386
+ * 传多个 `collectionKeys` 时分目录扫描,并按条目 key 去重——同一篇条目可能
387
+ * 同时挂在父分类与子分类里,不能重复计数。超过 `USAGE_SCAN_MAX` 条的大范围
388
+ * 按前若干页截断,超大目录可能漏掉靠后的标签(本地 API 没有按分类列标签的端点)。
389
+ */
390
+ export async function listTagUsage(options) {
391
+ const search = options.q?.trim() ?? '';
392
+ const counts = new Map();
393
+ const seenItems = new Set();
394
+ const bases = options.scope === 'publications'
395
+ ? [`${libraryBase()}/publications/items`]
396
+ : options.scope === 'trash'
397
+ ? [`${libraryBase()}/items/trash`]
398
+ : (options.collectionKeys ?? []).length > 0
399
+ ? options.collectionKeys.map((key) => `${libraryBase()}/collections/${encode(key)}/items/top`)
400
+ : [`${libraryBase()}/items/top`];
401
+ let scanned = 0;
402
+ for (const base of bases) {
403
+ for (let start = 0; scanned < USAGE_SCAN_MAX; start += USAGE_PAGE_SIZE) {
404
+ const params = new URLSearchParams({ limit: String(USAGE_PAGE_SIZE), start: String(start) });
405
+ if (search !== '')
406
+ params.set('q', search);
407
+ const { body } = await requestJson(`${base}?${params.toString()}`);
408
+ const page = Array.isArray(body) ? body : [];
409
+ if (page.length === 0)
410
+ break;
411
+ scanned += page.length;
412
+ for (const raw of page) {
413
+ if (seenItems.has(raw.key))
414
+ continue;
415
+ seenItems.add(raw.key);
416
+ // 「未分类条目」没有专用端点,与列表一样靠 data.collections 筛。
417
+ if (options.scope === 'unfiled' && (raw.data?.collections ?? []).length > 0)
418
+ continue;
419
+ for (const tag of raw.data?.tags ?? []) {
420
+ const name = tag.tag?.trim() ?? '';
421
+ if (name === '')
422
+ continue;
423
+ const existing = counts.get(name);
424
+ if (existing === undefined)
425
+ counts.set(name, { name, count: 1, type: tag.type ?? 1 });
426
+ else
427
+ existing.count += 1;
428
+ }
429
+ }
430
+ if (page.length < USAGE_PAGE_SIZE)
431
+ break;
432
+ }
433
+ if (scanned >= USAGE_SCAN_MAX)
434
+ break;
435
+ }
436
+ const tags = [...counts.values()];
437
+ return { total: tags.length, tags };
438
+ }
342
439
  /** 「未分类条目」推导时最多扫描的顶层条目数(避免超大口库长时间扫描)。 */
343
440
  const UNFILED_SCAN_MAX = 1000;
344
441
  /** 一页扫描条数(本地 API 上限 100)。 */
@@ -379,31 +476,50 @@ async function itemLastRead(key) {
379
476
  return null;
380
477
  }
381
478
  }
382
- /** 把 options 折成「顶层条目」端点基址 + 查询参数。 */
383
- function itemListQuery(options) {
384
- const base = options.scope === 'publications'
479
+ /** 把 `q` 与标签过滤写进查询参数(列表与未分类扫描共用)。 */
480
+ function appendItemFilters(params, options) {
481
+ if (options.q && options.q.trim() !== '')
482
+ params.set('q', options.q.trim());
483
+ const tags = (options.tags ?? []).map((tag) => tag.trim()).filter((tag) => tag !== '');
484
+ if (tags.length === 0)
485
+ return;
486
+ if (options.tagMode === 'any') {
487
+ params.set('tag', tags.join(' || '));
488
+ }
489
+ else {
490
+ for (const tag of tags)
491
+ params.append('tag', tag);
492
+ }
493
+ }
494
+ /** 范围内的顶层条目端点基址(条目列表与标签用量共用同一套范围规则)。 */
495
+ function itemListBase(options) {
496
+ return options.scope === 'publications'
385
497
  ? `${libraryBase()}/publications/items`
386
498
  : options.scope === 'trash'
387
499
  ? `${libraryBase()}/items/trash`
388
500
  : options.collectionKey
389
501
  ? `${libraryBase()}/collections/${encode(options.collectionKey)}/items/top`
390
502
  : `${libraryBase()}/items/top`;
503
+ }
504
+ /** 把 options 折成「顶层条目」端点基址 + 查询参数。 */
505
+ function itemListQuery(options) {
391
506
  const params = new URLSearchParams({
392
507
  limit: String(options.limit),
393
508
  start: String(options.offset),
394
509
  });
395
- if (options.q && options.q.trim() !== '')
396
- params.set('q', options.q.trim());
397
- return { base, params };
510
+ appendItemFilters(params, options);
511
+ return { base: itemListBase(options), params };
398
512
  }
399
513
  /**
400
514
  * 「未分类条目」:本地 API 没有专用端点,改为取顶层条目后筛掉已归类的
401
515
  * (`data.collections` 非空即已归类),分页在筛完后作用于结果集。
402
516
  */
403
- async function listUnfiled(offset, limit) {
517
+ async function listUnfiled(options) {
404
518
  const all = [];
405
519
  for (let start = 0; start < UNFILED_SCAN_MAX; start += PAGE_SIZE) {
406
- const { body } = await requestJson(`${libraryBase()}/items/top?limit=${PAGE_SIZE}&start=${start}`);
520
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE), start: String(start) });
521
+ appendItemFilters(params, options);
522
+ const { body } = await requestJson(`${libraryBase()}/items/top?${params.toString()}`);
407
523
  if (!Array.isArray(body) || body.length === 0)
408
524
  break;
409
525
  for (const raw of body) {
@@ -413,13 +529,13 @@ async function listUnfiled(offset, limit) {
413
529
  if (body.length < PAGE_SIZE)
414
530
  break;
415
531
  }
416
- const page = all.slice(offset, offset + limit);
532
+ const page = all.slice(options.offset, options.offset + options.limit);
417
533
  return { total: all.length, items: await toSummaries(page) };
418
534
  }
419
535
  /** 顶层条目列表(按虚拟分类、真实分类、或全库,或关键字搜索)。 */
420
536
  export async function listItems(options) {
421
537
  if (options.scope === 'unfiled')
422
- return listUnfiled(options.offset, options.limit);
538
+ return listUnfiled(options);
423
539
  const { base, params } = itemListQuery(options);
424
540
  const { body, total } = await requestJson(`${base}?${params.toString()}`);
425
541
  const raws = Array.isArray(body) ? body : [];
@@ -140,6 +140,18 @@ export interface ZoteroItems {
140
140
  total: number;
141
141
  items: ZoteroItemSummary[];
142
142
  }
143
+ /** 文库级标签(计数是全库的)。 */
144
+ export interface ZoteroTag {
145
+ name: string;
146
+ count: number;
147
+ /** 0 自动标签,1 手动标签。 */
148
+ type: number;
149
+ }
150
+ /** 标签列表数据。 */
151
+ export interface ZoteroTags {
152
+ total: number;
153
+ tags: ZoteroTag[];
154
+ }
143
155
  /** 分类引用导出数据。 */
144
156
  export interface ZoteroCollectionBib {
145
157
  bib: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-zotero",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Install this plugin and DSH can operate your Zotero for you: search the library, read PDF full text, summarize highlights and notes, organize collections by topic, import your downloaded papers, and attach a translated version back to an item. The right sidebar also gains a Zotero library panel that brings an item, an excerpt or a whole collection into the conversation with one click.",
5
5
  "keywords": [
6
6
  "dsh",