Files
store_ai_extension/src/background/service/taskState.ts
2026-05-06 10:52:45 +08:00

44 lines
1.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { CrawlTaskState } from '@/types';
// chrome.storage.local 中保存当前爬取任务状态的键名。
const CRAWL_TASK_STORAGE_KEY = 'crawlTaskState';
/**
* 从 chrome.storage.local 读取当前爬取任务状态。
*/
export async function getCrawlTaskState(): Promise<CrawlTaskState | null> {
const result = await chrome.storage.local.get(CRAWL_TASK_STORAGE_KEY);
const state = result[CRAWL_TASK_STORAGE_KEY];
return isCrawlTaskState(state) ? state : null;
}
/**
* 将最新爬取任务状态写入 chrome.storage.local供 popup 和 content script 同步读取。
*/
export async function setCrawlTaskState(state: CrawlTaskState): Promise<void> {
await chrome.storage.local.set({ [CRAWL_TASK_STORAGE_KEY]: state });
}
/**
* 读取任务状态后执行不可变更新,避免覆盖已取消或已替换的任务。
*/
export async function updateCrawlTaskState(
taskId: string,
updater: (state: CrawlTaskState) => CrawlTaskState,
): Promise<void> {
const state = await getCrawlTaskState();
if (!state || state.id !== taskId || state.status === 'canceled') {
return;
}
await setCrawlTaskState(updater(state));
}
/**
* 粗略判断 storage 中读取到的值是否像一个爬取任务状态对象。
*/
function isCrawlTaskState(value: unknown): value is CrawlTaskState {
return typeof value === 'object' && value !== null && 'id' in value && 'steps' in value;
}