import { describe, expect, it } from "vitest"; import { defaultExportConfig } from "@md-to-pdf/core"; import { EXPORT_CONFIG_STORAGE_KEY, LEGACY_EXPORT_CONFIG_STORAGE_KEY, loadExportConfig, parseStoredExportConfig, saveExportConfig } from "../src/export-settings"; function createMemoryStorage( initialValue: string | null = null, legacyValue: string | null = null ) { const values = new Map(); if (initialValue) { values.set(EXPORT_CONFIG_STORAGE_KEY, initialValue); } if (legacyValue) { values.set(LEGACY_EXPORT_CONFIG_STORAGE_KEY, legacyValue); } return { getItem(key: string) { return values.get(key) ?? null; }, setItem(key: string, nextValue: string) { values.set(key, nextValue); }, read() { return values.get(EXPORT_CONFIG_STORAGE_KEY) ?? null; } }; } describe("导出设置缓存", () => { it("在没有缓存时返回独立的默认配置", () => { const first = parseStoredExportConfig(null); const second = parseStoredExportConfig(null); expect(first).toEqual(defaultExportConfig); expect(first).not.toBe(second); }); it("缓存损坏或版本过期时恢复默认配置", () => { expect(parseStoredExportConfig("{")).toEqual(defaultExportConfig); expect( parseStoredExportConfig( JSON.stringify({ ...defaultExportConfig, version: 1 }) ) ).toEqual(defaultExportConfig); }); it("将 v2 缓存迁移为 v3 并保留已有设置", () => { const legacyConfig = { ...defaultExportConfig, version: 2, mermaid: undefined, paper: { ...defaultExportConfig.paper, format: "A5" } }; const storage = createMemoryStorage( null, JSON.stringify(legacyConfig) ); const migrated = loadExportConfig(storage); expect(migrated.version).toBe(3); expect(migrated.paper.format).toBe("A5"); expect(migrated.mermaid).toEqual(defaultExportConfig.mermaid); expect(storage.read()).toContain('"version":3'); }); it("保存并恢复经过校验的配置", () => { const storage = createMemoryStorage(); const config = { ...defaultExportConfig, paper: { ...defaultExportConfig.paper, format: "A3" as const, orientation: "landscape" as const } }; saveExportConfig(config, storage); expect(storage.read()).toContain('"format":"A3"'); expect(loadExportConfig(storage)).toEqual(config); }); });