AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add unified EdgeEver ZIP import and export
yomaeac2d16eddec
diff --git a/README.md b/README.mdindex 7c1a41c8..cba23fbb 100644--- a/README.md+++ b/README.md@@ -56,7 +56,7 @@ The automated helper commands are recommended. If you create the Cloudflare reso- Serverless, 100% free, and zero maintenance: Built on Cloudflare's Serverless architecture, running entirely within free tiers. Store up to 150k notes and 50k images without any hosting fees.- Open data: notes are stored in Cloudflare D1, based on standard SQLite, and can be read and managed through REST API, MCP, and CLI without locking your data to a single notes product.-- Markdown ZIP export: export active notes with Front Matter metadata, nested notebook structure, images, and attachments using portable relative paths.+- EdgeEver ZIP import and export: one archive combines human-readable Markdown, Front Matter, nested notebook structure, and relative-path attachments with versioned structured data and revision history for complete recovery between EdgeEver instances.- AI Agent friendly: built-in MCP support lets tools such as Codex, Claude Code, and Antigravity read, organize, and maintain notes, while enabling integrations with Notion databases and Feishu Bitable.- Uncapped multi-device sync: self-hosted API means no restrictive commercial limits on the number of active login devices, supporting seamless synchronization across PC, tablet, and mobile (via PWA or browser).- Three-pane layout: notebook tree, note list, and main editor.@@ -155,7 +155,7 @@ content_markdown API, Agent, import, and export formatcontent_text Search, summary, and indexing text```-To create a portable Markdown ZIP archive, open **Profile** -> **Export notes**. The export preserves notebook hierarchy and stores images and attachments alongside each note using relative paths.+Open **Profile** -> **Import and export** to export or import an EdgeEver ZIP. Its `notes/` directory is directly readable and portable as Markdown, while its structured data supports complete recovery between EdgeEver instances. Import preserves unrelated target data and overwrites records with matching EdgeEver IDs.## APIdiff --git a/README.zh-CN.md b/README.zh-CN.mdindex bfe37b48..d56b46b6 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -56,7 +56,7 @@ Agent 应优先按 [AI Agent Cloudflare Deployment](docs/agent-deploy-cloudflare- 零服务器,零运维,终身完全免费:基于 Cloudflare 无服务器架构与免费级配额,短笔记可达 15 万条,200KB 图片约可存放 5 万张,彻底免去云服务器租用和维护成本。- 数据完全开放:笔记内容存放在基于标准 SQLite 的 Cloudflare D1 中,可通过 REST API、MCP 和 CLI 按需读取与管理,不用担心被单一笔记产品绑定。-- Markdown ZIP 导出:可将有效笔记、Front Matter 元数据、嵌套笔记本结构、图片和附件完整导出,并使用便于迁移的相对路径。+- EdgeEver ZIP 导入与导出:同一份档案既包含便于直接阅读和迁移的 Markdown、Front Matter、嵌套笔记本结构与相对路径附件,也包含用于 EdgeEver 实例间完整恢复的版本化结构数据和历史版本。- AI Agent 友好:原生支持 MCP,可让 Codex、Claude Code、Antigravity 等工具读取、整理和维护笔记,并可借助 MCP 与 Notion Database、飞书多维表格进行联动。- 多端无缝同步且不限设备数:基于自建的 API 个人独享数据,摆脱商业笔记平台对登录设备数量的强制限制(如免费版只允许登录 2 台设备等),支持 PC、平板与手机无缝多端同步。- 三栏布局:笔记本树、笔记列表、主编辑区。@@ -157,7 +157,7 @@ content_markdown API、Agent、导入导出使用content_text 搜索、摘要和索引使用```-如需生成便于迁移的 Markdown ZIP 压缩包,请打开 **我的** -> **导出笔记**。导出内容会保留笔记本层级,并使用相对路径保存每篇笔记对应的图片和附件。+请打开 **我的** -> **导入与导出**,导出或导入 EdgeEver ZIP。压缩包中的 `notes/` 目录可直接作为 Markdown 阅读和迁移,结构化数据则用于在 EdgeEver 实例之间完整恢复;导入时目标实例中的无关数据会保留,相同 EdgeEver ID 的内容会被覆盖。## API 文档diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex c6e5977a..3fec7200 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -11,6 +11,7 @@ import {markdownToDoc,isSuspiciousMemoOverwrite,isMemoEditBindingValid,+ JsonBackupResourceMetadataSchema,MemoCreateSchema,MemoUpdateSchema,MergeMemosSchema,@@ -19,6 +20,8 @@ import {TagRenameSchema,NotebookCreateSchema,NotebookUpdateSchema,+ RestoreJsonMemosSchema,+ RestoreJsonNotebooksSchema,type ApiToken,type CreatedApiToken,type MemoDetail,@@ -26,6 +29,10 @@ import {type MemoRevision,type MemoSummary,type MemoUpdateInput,+ type JsonBackupMemo,+ type JsonBackupNotebook,+ type JsonBackupResource,+ type JsonBackupRevision,type Notebook,type NotebookCreateInput,type Resource,@@ -135,6 +142,8 @@ type MemoRevisionRow = {created_at: string;};+type BackupRevisionRow = MemoRevisionRow;+type MemoEditSessionRow = {id: string;memo_id: string;@@ -375,7 +384,7 @@ app.use(cors({origin: ["http://127.0.0.1:5173", "http://localhost:5173"],allowHeaders: ["Content-Type", "Authorization"],- allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],+ allowMethods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],credentials: true,}));@@ -1301,6 +1310,196 @@ app.get("/api/v1/exports/markdown", async (c) => {});});+app.get("/api/v1/backups/json", async (c) => {+ const denied = requireScopes(c, "read:memos", "read:resources");++ if (denied) {+ return denied;+ }++ const limit = clampNumber(Number(c.req.query("limit") ?? 25), 1, 50);+ const offset = clampNumber(Number(c.req.query("offset") ?? 0), 0, 1_000_000);+ const [memoRows, totalRow] = await Promise.all([+ c.env.DB.prepare(+ `SELECT m.id, m.notebook_id, m.title, m.excerpt, m.tags_json, m.is_pinned,+ m.is_archived, m.is_deleted, m.created_at, m.updated_at, m.deleted_at, mc.revision,+ mc.content_json, mc.content_markdown, mc.content_text, mc.content_hash,+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id+ FROM memos m+ INNER JOIN memo_contents mc ON mc.memo_id = m.id+ WHERE m.is_deleted = 0+ ORDER BY m.created_at ASC, m.id ASC+ LIMIT ? OFFSET ?`+ )+ .bind(limit, offset)+ .all<MemoDetailRow>(),+ c.env.DB.prepare(`SELECT COUNT(*) AS count FROM memos WHERE is_deleted = 0`).first<{ count: number }>(),+ ]);+ const memoIds = memoRows.results.map((row) => row.id);+ let resources: Resource[] = [];+ let revisions: JsonBackupRevision[] = [];++ if (memoIds.length > 0) {+ const placeholders = memoIds.map(() => "?").join(", ");+ const [resourceRows, revisionRows] = await Promise.all([+ c.env.DB.prepare(+ `SELECT id, memo_id, original_memo_id, bucket_name, object_key, kind, mime_type,+ filename, byte_size, sha256, width, height, created_at, updated_at+ FROM resources+ WHERE is_deleted = 0 AND memo_id IN (${placeholders})+ ORDER BY memo_id ASC, created_at ASC, id ASC`+ )+ .bind(...memoIds)+ .all<ResourceRow>(),+ c.env.DB.prepare(+ `SELECT id, memo_id, revision, title, tags_json, content_json, content_markdown,+ content_text, content_hash, created_by, created_at+ FROM memo_revisions+ WHERE memo_id IN (${placeholders})+ ORDER BY memo_id ASC, revision ASC, created_at ASC`+ )+ .bind(...memoIds)+ .all<BackupRevisionRow>(),+ ]);+ resources = resourceRows.results.map(mapResource);+ revisions = revisionRows.results.map(mapJsonBackupRevision);+ }++ const totalCount = totalRow?.count ?? memoRows.results.length;+ const nextOffset = offset + memoRows.results.length < totalCount ? offset + memoRows.results.length : null;++ return c.json({+ memos: memoRows.results.map(mapMemoDetail),+ resources,+ revisions,+ totalCount,+ nextOffset,+ });+});++app.post("/api/v1/restores/json/notebooks", zValidator("json", RestoreJsonNotebooksSchema), async (c) => {+ const userOnly = requireUser(c);+ if (userOnly) {+ return userOnly;+ }++ await restoreJsonNotebooks(c.env.DB, c.req.valid("json").notebooks as JsonBackupNotebook[]);+ return c.json({ ok: true });+});++app.post("/api/v1/restores/json/memos", zValidator("json", RestoreJsonMemosSchema), async (c) => {+ const userOnly = requireUser(c);+ if (userOnly) {+ return userOnly;+ }++ await restoreJsonMemos(c.env.DB, c.req.valid("json").memos as JsonBackupMemo[]);+ return c.json({ ok: true });+});++app.put("/api/v1/restores/json/resources/:id", async (c) => {+ const userOnly = requireUser(c);+ if (userOnly) {+ return userOnly;+ }++ const form = await c.req.raw.formData();+ const file = form.get("file");+ const metadataValue = form.get("metadata");+ if (!(file instanceof File) || typeof metadataValue !== "string") {+ return badRequest(c, "Restore resource file and metadata are required.");+ }++ let metadataInput: unknown;+ try {+ metadataInput = JSON.parse(metadataValue);+ } catch {+ return badRequest(c, "Restore resource metadata must be valid JSON.");+ }++ const parsed = JsonBackupResourceMetadataSchema.safeParse(metadataInput);+ if (!parsed.success || parsed.data.id !== c.req.param("id")) {+ return badRequest(c, "Restore resource metadata is invalid.");+ }++ const metadata = parsed.data as JsonBackupResource;+ const memo = await getMemoDetail(c.env.DB, metadata.memoId);+ if (!memo) {+ return notFound(c, "Restore target memo not found.");+ }++ const maxBytes = metadata.kind === "image" ? MAX_IMAGE_UPLOAD_BYTES : MAX_ATTACHMENT_UPLOAD_BYTES;+ if (file.size <= 0 || file.size > maxBytes) {+ return apiError(c, "upload_too_large", "Backup resource size is invalid.", 413);+ }++ const filename = normalizeFilename(metadata.filename || file.name) || `${metadata.kind}-${metadata.id}`;+ const objectKey = `restores/${metadata.memoId}/${metadata.id}/${Date.now()}-${filename}`;+ const bytes = new Uint8Array(await file.arrayBuffer());+ const previous = await c.env.DB.prepare(+ `SELECT object_key FROM resources WHERE id = ?`+ ).bind(metadata.id).first<{ object_key: string }>();+ const originalMemo = metadata.originalMemoId+ ? await c.env.DB.prepare(`SELECT id FROM memos WHERE id = ?`).bind(metadata.originalMemoId).first<{ id: string }>()+ : null;++ await c.env.RESOURCES.put(objectKey, bytes, {+ httpMetadata: { contentType: metadata.mimeType ?? file.type ?? "application/octet-stream" },+ customMetadata: { memoId: metadata.memoId, resourceId: metadata.id, restored: "true" },+ });++ try {+ const now = isoNow();+ await c.env.DB.prepare(+ `INSERT INTO resources (+ id, memo_id, original_memo_id, bucket_name, object_key, kind, mime_type, filename,+ byte_size, sha256, width, height, metadata_json, is_deleted, created_at, updated_at, deleted_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL)+ ON CONFLICT(id) DO UPDATE SET+ memo_id = excluded.memo_id,+ original_memo_id = excluded.original_memo_id,+ bucket_name = excluded.bucket_name,+ object_key = excluded.object_key,+ kind = excluded.kind,+ mime_type = excluded.mime_type,+ filename = excluded.filename,+ byte_size = excluded.byte_size,+ sha256 = excluded.sha256,+ width = excluded.width,+ height = excluded.height,+ metadata_json = excluded.metadata_json,+ is_deleted = 0,+ updated_at = excluded.updated_at,+ deleted_at = NULL`+ ).bind(+ metadata.id,+ metadata.memoId,+ originalMemo?.id ?? null,+ c.env.EDGE_EVER_R2_BUCKET_NAME?.trim() || DEFAULT_R2_BUCKET_NAME,+ objectKey,+ metadata.kind,+ metadata.mimeType ?? file.type ?? null,+ filename,+ bytes.byteLength,+ await sha256Bytes(bytes),+ metadata.width,+ metadata.height,+ JSON.stringify({ source: "edgeever-zip-import" }),+ metadata.createdAt,+ now+ ).run();+ } catch (error) {+ await c.env.RESOURCES.delete(objectKey);+ throw error;+ }++ if (previous?.object_key && previous.object_key !== objectKey) {+ await c.env.RESOURCES.delete(previous.object_key);+ }++ return c.json({ ok: true });+});+app.get("/api/v1/resources", async (c) => {const denied = requireScopes(c, "read:resources");@@ -3377,6 +3576,172 @@ const mapMemoRevision = (row: MemoRevisionRow): MemoRevision => ({createdAt: row.created_at,});+const mapJsonBackupRevision = (row: BackupRevisionRow): JsonBackupRevision => ({+ id: row.id,+ memoId: row.memo_id,+ revision: row.revision,+ title: row.title,+ tags: parseJsonArray(row.tags_json),+ contentJson: parseDoc(row.content_json),+ contentMarkdown: row.content_markdown,+ contentText: row.content_text,+ contentHash: row.content_hash,+ createdBy: row.created_by,+ createdAt: row.created_at,+});++const restoreJsonNotebooks = async (db: D1Database, notebooks: JsonBackupNotebook[]) => {+ const statements = notebooks.map((notebook) =>+ db.prepare(+ `INSERT INTO notebooks (+ id, parent_id, name, slug, icon, color, sort_order, is_deleted, created_at, updated_at, deleted_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL)+ ON CONFLICT(id) DO UPDATE SET+ parent_id = excluded.parent_id,+ name = excluded.name,+ slug = excluded.slug,+ icon = excluded.icon,+ color = excluded.color,+ sort_order = excluded.sort_order,+ is_deleted = 0,+ updated_at = excluded.updated_at,+ deleted_at = NULL`+ ).bind(+ notebook.id,+ notebook.parentId,+ notebook.name,+ notebook.slug,+ notebook.icon,+ notebook.color,+ notebook.sortOrder,+ notebook.createdAt,+ notebook.updatedAt+ )+ );++ await db.batch(statements);+};++const restoreJsonMemos = async (db: D1Database, backups: JsonBackupMemo[]) => {+ for (const backup of backups) {+ const memo = backup.memo;+ const contentJson = parseDoc(JSON.stringify(memo.contentJson));+ const contentMarkdown = memo.contentMarkdown || docToMarkdown(contentJson);+ const contentText = docToText(contentJson);+ const contentHash = await sha256(contentMarkdown + JSON.stringify(contentJson));+ const title = normalizeMemoTitle(memo.title);+ const tags = normalizeTags(memo.tags);++ if (backup.revisions.some((revision) => revision.memoId !== memo.id)) {+ throw new AppError("invalid_backup", "A backup revision belongs to a different memo.", 400);+ }++ await db.batch([+ db.prepare(+ `INSERT INTO memos (+ id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted,+ source_memo_ids, merge_source_count, merged_into_memo_id,+ created_by, updated_by, created_at, updated_at, deleted_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, NULL, 'restore', 'restore', ?, ?, NULL)+ ON CONFLICT(id) DO UPDATE SET+ notebook_id = excluded.notebook_id,+ title = excluded.title,+ excerpt = excluded.excerpt,+ tags_json = excluded.tags_json,+ is_pinned = excluded.is_pinned,+ is_archived = excluded.is_archived,+ is_deleted = 0,+ source_memo_ids = excluded.source_memo_ids,+ merge_source_count = excluded.merge_source_count,+ merged_into_memo_id = NULL,+ updated_by = 'restore',+ updated_at = excluded.updated_at,+ deleted_at = NULL`+ ).bind(+ memo.id,+ memo.notebookId,+ title,+ createExcerpt(contentText),+ JSON.stringify(tags),+ memo.isPinned ? 1 : 0,+ memo.isArchived ? 1 : 0,+ JSON.stringify(memo.sourceMemoIds),+ memo.mergeSourceCount,+ memo.createdAt,+ memo.updatedAt+ ),+ db.prepare(+ `INSERT INTO memo_contents (+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(memo_id) DO UPDATE SET+ content_json = excluded.content_json,+ content_markdown = excluded.content_markdown,+ content_text = excluded.content_text,+ content_hash = excluded.content_hash,+ revision = excluded.revision,+ updated_at = excluded.updated_at`+ ).bind(+ memo.id,+ JSON.stringify(contentJson),+ contentMarkdown,+ contentText,+ contentHash,+ memo.revision,+ memo.createdAt,+ memo.updatedAt+ ),+ db.prepare(`DELETE FROM memos_fts WHERE memo_id = ?`).bind(memo.id),+ db.prepare(+ `INSERT INTO memos_fts (memo_id, title, content_text, tags) VALUES (?, ?, ?, ?)`+ ).bind(memo.id, title, contentText, tags.join(" ")),+ db.prepare(`DELETE FROM memo_revisions WHERE memo_id = ?`).bind(memo.id),+ ]);++ for (let index = 0; index < backup.revisions.length; index += 50) {+ const statements = backup.revisions.slice(index, index + 50).map((revision) => {+ const revisionJson = parseDoc(JSON.stringify(revision.contentJson));+ const revisionMarkdown = revision.contentMarkdown || docToMarkdown(revisionJson);+ const revisionText = docToText(revisionJson);+ return db.prepare(+ `INSERT INTO memo_revisions (+ id, memo_id, revision, title, content_json, content_markdown,+ content_hash, created_by, created_at, tags_json, content_text+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ memo_id = excluded.memo_id,+ revision = excluded.revision,+ title = excluded.title,+ content_json = excluded.content_json,+ content_markdown = excluded.content_markdown,+ content_hash = excluded.content_hash,+ created_by = excluded.created_by,+ created_at = excluded.created_at,+ tags_json = excluded.tags_json,+ content_text = excluded.content_text`+ ).bind(+ revision.id,+ memo.id,+ revision.revision,+ normalizeMemoTitle(revision.title),+ JSON.stringify(revisionJson),+ revisionMarkdown,+ revision.contentHash || "",+ revision.createdBy,+ revision.createdAt,+ JSON.stringify(normalizeTags(revision.tags)),+ revisionText+ );+ });+ await db.batch(statements);+ }+ }++ await audit(db, "user", null, "backup.restore", "backup", createId("restore"), {+ memoCount: backups.length,+ });+};+const mapResource = (row: ResourceRow): Resource => ({id: row.id,memoId: row.memo_id,diff --git a/apps/web/src/components/settings/DataExportCard.tsx b/apps/web/src/components/settings/DataExportCard.tsxindex 2e6c6c65..c08b79d9 100644--- a/apps/web/src/components/settings/DataExportCard.tsx+++ b/apps/web/src/components/settings/DataExportCard.tsx@@ -1,96 +1,168 @@-import { useState } from "react";-import { AlertCircle, CheckCircle2, Download } from "lucide-react";+import { useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { AlertCircle, CheckCircle2, DatabaseBackup, Download, Upload } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import { api } from "@/lib/api";-import { createMarkdownExport, downloadMarkdownExport, type MarkdownExportProgress } from "@/lib/markdown-export";+import {+ createEdgeEverZip,+ downloadEdgeEverZip,+ parseEdgeEverZip,+ restoreEdgeEverZip,+ type EdgeEverZipProgress,+ type ParsedEdgeEverZip,+} from "@/lib/json-backup";-type ExportState = "idle" | "exporting" | "complete" | "error";+type OperationState = "idle" | "working" | "complete" | "error";+type OperationKind = "export" | "import";++const Progress = ({ progress }: { progress: EdgeEverZipProgress }) => {+ const percentage = progress.total > 0 ? Math.round((progress.completed / progress.total) * 100) : 0;+ return (+ <div className="h-1.5 overflow-hidden rounded-full bg-slate-200">+ <div className="h-full rounded-full bg-emerald-600 transition-[width]" style={{ width: `${percentage}%` }} />+ </div>+ );+};export const DataExportCard = () => {const { t } = useTranslation();- const [state, setState] = useState<ExportState>("idle");- const [progress, setProgress] = useState<MarkdownExportProgress>({ completed: 0, total: 0 });+ const queryClient = useQueryClient();+ const fileInputRef = useRef<HTMLInputElement>(null);+ const [state, setState] = useState<OperationState>("idle");+ const [operation, setOperation] = useState<OperationKind>("export");+ const [progress, setProgress] = useState<EdgeEverZipProgress>({ completed: 0, total: 0 });+ const [pendingImport, setPendingImport] = useState<ParsedEdgeEverZip | null>(null);++ const busy = state === "working";const handleExport = async () => {- setState("exporting");+ setOperation("export");+ setState("working");setProgress({ completed: 0, total: 0 });+ try {+ const blob = await createEdgeEverZip(+ { listNotebooks: api.listNotebooks, getPage: api.getJsonBackupPage, getResourceBlob: api.getResourceBlob },+ { edgeeverVersion: __EDGEEVER_APP_VERSION__, buildId: __EDGEEVER_BUILD_ID__ },+ setProgress+ );+ downloadEdgeEverZip(blob);+ setState("complete");+ } catch (error) {+ console.error("Failed to export EdgeEver ZIP", error);+ setState("error");+ }+ };+ const handleImportFile = async (file: File | undefined) => {+ if (!file) return;+ setOperation("import");+ setState("working");+ setProgress({ completed: 0, total: 0 });try {- const blob = await createMarkdownExport(+ const parsed = await parseEdgeEverZip(file);+ setPendingImport(parsed);+ setState("idle");+ } catch (error) {+ console.error("Invalid EdgeEver ZIP", error);+ setState("error");+ } finally {+ if (fileInputRef.current) fileInputRef.current.value = "";+ }+ };++ const handleConfirmImport = async () => {+ if (!pendingImport) return;+ const archive = pendingImport;+ setPendingImport(null);+ setOperation("import");+ setState("working");+ setProgress({ completed: 0, total: 0 });+ try {+ await restoreEdgeEverZip(+ archive,{- listNotebooks: api.listNotebooks,- getPage: api.getMarkdownExportPage,- getResourceBlob: api.getResourceBlob,+ restoreNotebooks: api.restoreJsonNotebooks,+ restoreMemos: api.restoreJsonMemos,+ restoreResource: api.restoreJsonResource,},setProgress);- downloadMarkdownExport(blob);+ await queryClient.invalidateQueries();setState("complete");} catch (error) {- console.error("Failed to export Markdown ZIP", error);+ console.error("Failed to import EdgeEver ZIP", error);setState("error");}};- const percentage = progress.total > 0 ? Math.round((progress.completed / progress.total) * 100) : 0;-return (- <Card className="w-full min-w-0 overflow-hidden shadow-none">- <CardHeader className="p-4 pb-3">- <CardTitle className="flex items-center gap-2 text-sm">- <Download className="h-4 w-4 text-emerald-700" />- {t("dataExport.title")}- </CardTitle>- </CardHeader>- <CardContent className="grid gap-3 p-4 pt-0">- <div className="grid gap-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-center">- <CardDescription className="min-w-0 text-xs leading-5 md:truncate">- {t("dataExport.description")}- </CardDescription>- <Button- size="sm"- type="button"- className="w-full whitespace-nowrap md:w-auto"- disabled={state === "exporting"}- onClick={() => void handleExport()}- >- <Download className="h-4 w-4" />- {state === "exporting" ? t("dataExport.exportingButton") : t("dataExport.exportButton")}- </Button>- </div>-- {state === "exporting" ? (- <div className="grid gap-1.5" aria-live="polite">- <div className="flex items-center justify-between text-xs text-slate-500">- <span>{t("dataExport.exporting")}</span>- <span>{t("dataExport.progress", { completed: progress.completed, total: progress.total })}</span>+ <>+ <Card className="w-full min-w-0 overflow-hidden shadow-none">+ <CardHeader className="p-4 pb-3">+ <CardTitle className="flex items-center gap-2 text-sm">+ <DatabaseBackup className="h-4 w-4 text-emerald-700" />+ {t("dataExport.title")}+ </CardTitle>+ </CardHeader>+ <CardContent className="grid gap-3 p-4 pt-0">+ <div className="grid gap-2 rounded-lg border border-slate-200 p-3 md:grid-cols-[minmax(0,1fr)_auto] md:items-center">+ <div className="min-w-0">+ <CardDescription className="text-xs leading-5">{t("dataExport.description")}</CardDescription></div>- <div className="h-1.5 overflow-hidden rounded-full bg-slate-200">- <div- className="h-full rounded-full bg-emerald-600 transition-[width]"- style={{ width: `${percentage}%` }}- />+ <div className="flex flex-col gap-2 sm:flex-row">+ <Button size="sm" variant="outline" type="button" disabled={busy} onClick={() => fileInputRef.current?.click()}>+ <Upload className="h-4 w-4" />+ {t("dataExport.importButton")}+ </Button>+ <Button size="sm" type="button" disabled={busy} onClick={() => void handleExport()}>+ <Download className="h-4 w-4" />+ {t("dataExport.exportButton")}+ </Button>+ <input ref={fileInputRef} className="hidden" type="file" accept=".zip,application/zip" onChange={(event) => void handleImportFile(event.target.files?.[0])} /></div></div>- ) : null}-- {state === "complete" ? (- <p className="flex items-center gap-1.5 text-xs text-emerald-700" aria-live="polite">- <CheckCircle2 className="h-3.5 w-3.5" />- {t("dataExport.complete")}- </p>- ) : null}- {state === "error" ? (- <p className="flex items-center gap-1.5 text-xs text-red-600" role="alert">- <AlertCircle className="h-3.5 w-3.5" />- {t("dataExport.error")}- </p>- ) : null}+ {busy ? (+ <div className="grid gap-1.5" aria-live="polite">+ <div className="flex items-center justify-between text-xs text-slate-500">+ <span>{operation === "import" ? t("dataExport.importing") : t("dataExport.working")}</span>+ <span>{t("dataExport.progress", { completed: progress.completed, total: progress.total })}</span>+ </div>+ <Progress progress={progress} />+ </div>+ ) : null}+ {state === "complete" ? <p className="flex items-center gap-1.5 text-xs text-emerald-700"><CheckCircle2 className="h-3.5 w-3.5" />{operation === "import" ? t("dataExport.importComplete") : t("dataExport.complete")}</p> : null}+ {state === "error" ? <p className="flex items-center gap-1.5 text-xs text-red-600" role="alert"><AlertCircle className="h-3.5 w-3.5" />{operation === "import" ? t("dataExport.importError") : t("dataExport.error")}</p> : null}+ </CardContent>+ </Card>- </CardContent>- </Card>+ <Dialog open={Boolean(pendingImport)} onOpenChange={(open) => { if (!open) setPendingImport(null); }}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t("dataExport.importConfirmTitle")}</DialogTitle>+ <DialogDescription>+ {t("dataExport.importConfirmDescription", {+ memos: pendingImport?.manifest.counts.memos ?? 0,+ resources: pendingImport?.manifest.counts.resources ?? 0,+ })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button variant="outline" type="button" onClick={() => setPendingImport(null)}>{t("common.cancel")}</Button>+ <Button type="button" onClick={() => void handleConfirmImport()}>{t("dataExport.confirmImport")}</Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>);};diff --git a/apps/web/src/i18n/resources/en-US.ts b/apps/web/src/i18n/resources/en-US.tsindex 8c349c60..34a87d8a 100644--- a/apps/web/src/i18n/resources/en-US.ts+++ b/apps/web/src/i18n/resources/en-US.ts@@ -164,14 +164,20 @@ export const enUS = {copy: "Copy info",},dataExport: {- title: "Export notes",- description: "Export active notes as a Markdown ZIP with Front Matter and .assets attachments; Trash is excluded.",- exportButton: "Export Markdown ZIP",- exportingButton: "Exporting",- exporting: "Preparing notes and attachments…",- progress: "{{completed}} / {{total}} notes",+ title: "Import and export",+ description: "One archive for openness and complete recovery: read notes directly as Markdown, or use the structured data, revision history, and attachments to migrate between EdgeEver instances.",+ exportButton: "Export EdgeEver ZIP",+ importButton: "Import EdgeEver ZIP",+ working: "Preparing notes and attachments…",+ importing: "Importing notes and attachments…",+ progress: "{{completed}} / {{total}}",complete: "Export complete. Your ZIP download has started.",error: "Export failed. Check your connection and try again.",+ importComplete: "EdgeEver ZIP imported successfully.",+ importError: "The file is invalid or could not be imported. Make sure it is an EdgeEver ZIP and check your connection.",+ importConfirmTitle: "Import EdgeEver ZIP",+ importConfirmDescription: "This file contains {{memos}} notes and {{resources}} resources. Other data in this instance is preserved, but matching EdgeEver IDs are overwritten.",+ confirmImport: "Import",},shortcuts: {title: "Keyboard shortcuts",diff --git a/apps/web/src/i18n/resources/zh-CN.ts b/apps/web/src/i18n/resources/zh-CN.tsindex 1fd02b0e..4ad73c66 100644--- a/apps/web/src/i18n/resources/zh-CN.ts+++ b/apps/web/src/i18n/resources/zh-CN.ts@@ -164,14 +164,20 @@ export const zhCN = {copy: "复制信息",},dataExport: {- title: "导出笔记",- description: "将当前工作区中的有效笔记导出为 Markdown ZIP,元数据写入 Front Matter,附件存入 .assets,不含回收站内容。",- exportButton: "导出 Markdown ZIP",- exportingButton: "正在导出",- exporting: "正在整理笔记和附件…",- progress: "{{completed}} / {{total}} 篇",+ title: "导入与导出",+ description: "一份同时兼顾开放性与完整恢复的档案:笔记可直接以 Markdown 阅读,结构化数据、历史版本和附件可用于 EdgeEver 实例间迁移。",+ exportButton: "导出 EdgeEver ZIP",+ importButton: "导入 EdgeEver ZIP",+ working: "正在整理笔记和附件…",+ importing: "正在导入笔记和附件…",+ progress: "{{completed}} / {{total}}",complete: "导出完成,ZIP 文件已开始下载。",error: "导出失败,请检查网络连接后重试。",+ importComplete: "EdgeEver ZIP 导入完成。",+ importError: "文件无效或导入失败,请确认它是 EdgeEver ZIP 并检查网络连接。",+ importConfirmTitle: "导入 EdgeEver ZIP",+ importConfirmDescription: "文件包含 {{memos}} 篇笔记和 {{resources}} 个资源。导入会保留当前实例中的其他数据,但会覆盖相同 EdgeEver ID 的内容。",+ confirmImport: "确认导入",},shortcuts: {title: "绑定快捷键",diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 20dc90f6..6a72f6ad 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -2,6 +2,9 @@ import type {AuthSession,ApiToken,CreatedApiToken,+ JsonBackupMemo,+ JsonBackupNotebook,+ JsonBackupRevision,MemoDetail,MemoEditSession,MemoRevision,@@ -62,6 +65,10 @@ export type MarkdownExportPage = {nextOffset: number | null;};+export type JsonBackupPage = MarkdownExportPage & {+ revisions: JsonBackupRevision[];+};+export class ApiRequestError extends Error {status: number;code?: string;@@ -267,6 +274,31 @@ export const api = {getMarkdownExportPage: (offset = 0, limit = 50) =>request<MarkdownExportPage>(`/api/v1/exports/markdown?offset=${offset}&limit=${limit}`),+ getJsonBackupPage: (offset = 0, limit = 25) =>+ request<JsonBackupPage>(`/api/v1/backups/json?offset=${offset}&limit=${limit}`),++ restoreJsonNotebooks: (notebooks: JsonBackupNotebook[]) =>+ request<{ ok: true }>("/api/v1/restores/json/notebooks", {+ method: "POST",+ body: JSON.stringify({ notebooks }),+ }),++ restoreJsonMemos: (memos: JsonBackupMemo[]) =>+ request<{ ok: true }>("/api/v1/restores/json/memos", {+ method: "POST",+ body: JSON.stringify({ memos }),+ }),++ restoreJsonResource: (resourceId: string, metadata: JsonBackupMemo["resources"][number], file: Blob) => {+ const form = new FormData();+ form.append("metadata", JSON.stringify(metadata));+ form.append("file", file, metadata.filename || metadata.id);+ return request<{ ok: true }>(`/api/v1/restores/json/resources/${encodeURIComponent(resourceId)}`, {+ method: "PUT",+ body: form,+ });+ },+getResourceBlob: async (resourceUrl: string) => {const response = await fetch(resourceUrl, { credentials: "include" });diff --git a/apps/web/src/lib/json-backup.ts b/apps/web/src/lib/json-backup.tsnew file mode 100644index 00000000..e84a73ef--- /dev/null+++ b/apps/web/src/lib/json-backup.ts@@ -0,0 +1,325 @@+import {+ EDGEEVER_ZIP_FORMAT,+ EDGEEVER_ZIP_FORMAT_VERSION,+ JsonBackupManifestSchema,+ JsonBackupMemoSchema,+ JsonBackupNotebookSchema,+ type JsonBackupManifest,+ type JsonBackupMemo,+ type JsonBackupNotebook,+ type JsonBackupResource,+ type JsonBackupRevision,+ type MemoDetail,+ type Notebook,+ type Resource,+} from "@edgeever/shared";+import { strFromU8, strToU8, unzip, Zip, ZipDeflate, ZipPassThrough } from "fflate";+import {+ buildMarkdownFrontMatter,+ buildNotebookExportPaths,+ getExportResourceExtension,+ replaceExportResourceUrl,+ sanitizeExportPathSegment,+ uniqueExportName,+} from "./markdown-export";++export type EdgeEverZipProgress = {+ completed: number;+ total: number;+};++type JsonBackupPage = {+ memos: MemoDetail[];+ resources: Resource[];+ revisions: JsonBackupRevision[];+ totalCount: number;+ nextOffset: number | null;+};++type JsonBackupSource = {+ listNotebooks: () => Promise<{ notebooks: Notebook[] }>;+ getPage: (offset: number, limit: number) => Promise<JsonBackupPage>;+ getResourceBlob: (resourceUrl: string) => Promise<Blob>;+};++type JsonRestoreTarget = {+ restoreNotebooks: (notebooks: JsonBackupNotebook[]) => Promise<unknown>;+ restoreMemos: (memos: JsonBackupMemo[]) => Promise<unknown>;+ restoreResource: (resourceId: string, metadata: JsonBackupResource, file: Blob) => Promise<unknown>;+};++export type ParsedEdgeEverZip = {+ manifest: JsonBackupManifest;+ notebooks: JsonBackupNotebook[];+ memos: JsonBackupMemo[];+ files: Record<string, Uint8Array>;+};++const PAGE_SIZE = 25;+const ZIP_MIME_TYPE = "application/zip";+const jsonBytes = (value: unknown) => strToU8(`${JSON.stringify(value, null, 2)}\n`);++const addJsonFile = (zip: Zip, path: string, value: unknown) => {+ const file = new ZipDeflate(path, { level: 6 });+ zip.add(file);+ file.push(jsonBytes(value), true);+};++const toBackupNotebook = (notebook: Notebook): JsonBackupNotebook => ({+ id: notebook.id,+ parentId: notebook.parentId,+ name: notebook.name,+ slug: notebook.slug,+ icon: notebook.icon,+ color: notebook.color,+ sortOrder: notebook.sortOrder,+ createdAt: notebook.createdAt,+ updatedAt: notebook.updatedAt,+});++export const createEdgeEverZip = async (+ source: JsonBackupSource,+ version: { edgeeverVersion: string; buildId: string },+ onProgress?: (progress: EdgeEverZipProgress) => void+) => {+ const { notebooks } = await source.listNotebooks();+ const notebookPaths = buildNotebookExportPaths(notebooks);+ const memoNamesByNotebook = new Map<string, Set<string>>();+ const chunks: ArrayBuffer[] = [];++ return new Promise<Blob>((resolve, reject) => {+ const zip = new Zip((error, data, final) => {+ if (error) {+ reject(error);+ return;+ }+ chunks.push(new Uint8Array(data).buffer);+ if (final) {+ resolve(new Blob(chunks, { type: ZIP_MIME_TYPE }));+ }+ });++ void (async () => {+ try {+ const backupNotebooks = notebooks.map(toBackupNotebook);+ addJsonFile(zip, "notebooks.json", backupNotebooks);+ let offset = 0;+ let completed = 0;+ let total = 0;+ let revisionCount = 0;+ let resourceCount = 0;++ while (true) {+ const page = await source.getPage(offset, PAGE_SIZE);+ total = page.totalCount;+ onProgress?.({ completed, total });+ const resourcesByMemo = new Map<string, Resource[]>();+ const revisionsByMemo = new Map<string, JsonBackupRevision[]>();++ for (const resource of page.resources) {+ const items = resourcesByMemo.get(resource.memoId) ?? [];+ items.push(resource);+ resourcesByMemo.set(resource.memoId, items);+ }+ for (const revision of page.revisions) {+ const items = revisionsByMemo.get(revision.memoId) ?? [];+ items.push(revision);+ revisionsByMemo.set(revision.memoId, items);+ }++ for (const memo of page.memos) {+ const notebookPath = notebookPaths.get(memo.notebookId) ?? "Unfiled";+ const usedMemoNames = memoNamesByNotebook.get(notebookPath) ?? new Set<string>();+ memoNamesByNotebook.set(notebookPath, usedMemoNames);+ const memoStem = uniqueExportName(+ sanitizeExportPathSegment(memo.title?.trim() || "Untitled note", "Untitled note"),+ usedMemoNames+ );+ const markdownDirectory = `notes/${notebookPath}`;+ const assetDirectory = `${memoStem}.assets`;+ const usedResourceNames = new Set<string>();+ let markdown = memo.contentMarkdown;+ const backupResources: JsonBackupResource[] = [];+ for (const resource of resourcesByMemo.get(memo.id) ?? []) {+ const fallbackName = `${resource.kind}-${resource.id}.${getExportResourceExtension(resource)}`;+ const filename = uniqueExportName(+ sanitizeExportPathSegment(resource.filename || fallbackName, fallbackName),+ usedResourceNames+ );+ const relativePath = `${assetDirectory}/${filename}`;+ const archivePath = `${markdownDirectory}/${relativePath}`;+ const blob = await source.getResourceBlob(resource.url);+ const file = new ZipPassThrough(archivePath);+ zip.add(file);+ file.push(new Uint8Array(await blob.arrayBuffer()), true);+ backupResources.push({+ id: resource.id,+ memoId: resource.memoId,+ originalMemoId: resource.originalMemoId,+ kind: resource.kind,+ mimeType: resource.mimeType,+ filename: resource.filename,+ byteSize: resource.byteSize,+ sha256: resource.sha256,+ width: resource.width,+ height: resource.height,+ createdAt: resource.createdAt,+ updatedAt: resource.updatedAt,+ archivePath,+ });+ markdown = replaceExportResourceUrl(markdown, resource.url, relativePath);+ resourceCount += 1;+ }++ const revisions = revisionsByMemo.get(memo.id) ?? [];+ addJsonFile(zip, `memos/${memo.id}.json`, { memo, revisions, resources: backupResources });+ const markdownFile = new ZipDeflate(`${markdownDirectory}/${memoStem}.md`, { level: 6 });+ zip.add(markdownFile);+ markdownFile.push(strToU8(`${buildMarkdownFrontMatter(memo, notebookPath)}${markdown}`), true);+ revisionCount += revisions.length;+ completed += 1;+ onProgress?.({ completed, total });+ }++ if (page.nextOffset === null) {+ break;+ }+ offset = page.nextOffset;+ }++ const manifest: JsonBackupManifest = {+ format: EDGEEVER_ZIP_FORMAT,+ formatVersion: EDGEEVER_ZIP_FORMAT_VERSION,+ schemaVersion: 1,+ edgeeverVersion: version.edgeeverVersion,+ buildId: version.buildId,+ exportedAt: new Date().toISOString(),+ includesTrash: false,+ counts: {+ notebooks: backupNotebooks.length,+ memos: total,+ revisions: revisionCount,+ resources: resourceCount,+ },+ };+ addJsonFile(zip, "manifest.json", manifest);+ zip.end();+ } catch (error) {+ zip.terminate();+ reject(error);+ }+ })();+ });+};++const parseJsonFile = (files: Record<string, Uint8Array>, path: string) => {+ const data = files[path];+ if (!data) {+ throw new Error(`Backup file is missing: ${path}`);+ }+ return JSON.parse(strFromU8(data)) as unknown;+};++const unzipBlob = async (blob: Blob) => {+ const bytes = new Uint8Array(await blob.arrayBuffer());+ return new Promise<Record<string, Uint8Array>>((resolve, reject) => {+ unzip(bytes, (error, files) => error ? reject(error) : resolve(files));+ });+};++const sortNotebooksForRestore = (notebooks: JsonBackupNotebook[]) => {+ const byId = new Map(notebooks.map((notebook) => [notebook.id, notebook]));+ const depth = (notebook: JsonBackupNotebook, seen = new Set<string>()): number => {+ if (!notebook.parentId || !byId.has(notebook.parentId) || seen.has(notebook.id)) {+ return 0;+ }+ seen.add(notebook.id);+ return 1 + depth(byId.get(notebook.parentId)!, seen);+ };+ return [...notebooks].sort((left, right) => depth(left) - depth(right));+};++export const parseEdgeEverZip = async (blob: Blob): Promise<ParsedEdgeEverZip> => {+ const files = await unzipBlob(blob);+ const manifest = JsonBackupManifestSchema.parse(parseJsonFile(files, "manifest.json"));+ const notebooksValue = parseJsonFile(files, "notebooks.json");+ if (!Array.isArray(notebooksValue)) {+ throw new Error("notebooks.json must contain an array.");+ }+ const notebooks = sortNotebooksForRestore(notebooksValue.map((item) => JsonBackupNotebookSchema.parse(item)));+ const memoPaths = Object.keys(files).filter((path) => /^memos\/[^/]+\.json$/.test(path)).sort();+ const memos = memoPaths.map((path) => JsonBackupMemoSchema.parse(parseJsonFile(files, path)) as JsonBackupMemo);+ const markdownCount = Object.keys(files).filter((path) => /^notes\/.+\.md$/.test(path)).length;++ if (+ manifest.counts.notebooks !== notebooks.length+ || manifest.counts.memos !== memos.length+ || manifest.counts.memos !== markdownCount+ ) {+ throw new Error("Backup manifest counts do not match the archive contents.");+ }++ const resources = memos.flatMap((memo) => memo.resources);+ const revisionCount = memos.reduce((count, memo) => count + memo.revisions.length, 0);+ if (manifest.counts.revisions !== revisionCount) {+ throw new Error("Backup revisions are incomplete.");+ }+ if (+ manifest.counts.resources !== resources.length+ || resources.some((resource) => !files[resource.archivePath] || files[resource.archivePath].byteLength !== resource.byteSize)+ ) {+ throw new Error("Backup resources are incomplete.");+ }++ return { manifest, notebooks, memos, files };+};++export const restoreEdgeEverZip = async (+ backup: ParsedEdgeEverZip,+ target: JsonRestoreTarget,+ onProgress?: (progress: EdgeEverZipProgress) => void+) => {+ const total = backup.notebooks.length + backup.memos.length + backup.manifest.counts.resources;+ let completed = 0;+ onProgress?.({ completed, total });++ for (let index = 0; index < backup.notebooks.length; index += 100) {+ const batch = backup.notebooks.slice(index, index + 100);+ await target.restoreNotebooks(batch);+ completed += batch.length;+ onProgress?.({ completed, total });+ }++ for (let index = 0; index < backup.memos.length; index += 10) {+ const batch = backup.memos.slice(index, index + 10);+ await target.restoreMemos(batch);+ completed += batch.length;+ onProgress?.({ completed, total });+ }++ for (const memo of backup.memos) {+ for (const resource of memo.resources) {+ await target.restoreResource(+ resource.id,+ resource,+ new Blob([new Uint8Array(backup.files[resource.archivePath])], {+ type: resource.mimeType || "application/octet-stream",+ })+ );+ completed += 1;+ onProgress?.({ completed, total });+ }+ }+};++export const downloadEdgeEverZip = (blob: Blob) => {+ const date = new Date().toISOString().slice(0, 10);+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement("a");+ anchor.href = url;+ anchor.download = `edgeever-export-${date}.zip`;+ document.body.appendChild(anchor);+ anchor.click();+ anchor.remove();+ window.setTimeout(() => URL.revokeObjectURL(url), 1_000);+};diff --git a/apps/web/src/lib/markdown-export.ts b/apps/web/src/lib/markdown-export.tsindex 19f9fe08..1b88e09f 100644--- a/apps/web/src/lib/markdown-export.ts+++ b/apps/web/src/lib/markdown-export.ts@@ -34,7 +34,7 @@ export const sanitizeExportPathSegment = (value: string, fallback: string) => {return WINDOWS_RESERVED_NAME.test(safeValue) ? `_${safeValue}` : safeValue;};-const uniqueName = (candidate: string, usedNames: Set<string>) => {+export const uniqueExportName = (candidate: string, usedNames: Set<string>) => {if (!usedNames.has(candidate.toLocaleLowerCase())) {usedNames.add(candidate.toLocaleLowerCase());return candidate;@@ -61,7 +61,7 @@ export const buildNotebookExportPaths = (notebooks: Notebook[]) => {siblingNames.set(parentKey, usedNames);segmentById.set(notebook.id,- uniqueName(sanitizeExportPathSegment(notebook.name, "Untitled notebook"), usedNames)+ uniqueExportName(sanitizeExportPathSegment(notebook.name, "Untitled notebook"), usedNames));}@@ -109,7 +109,7 @@ export const buildMarkdownFrontMatter = (memo: MemoDetail, notebookPath: string)"",].join("\n");-const getExtension = (resource: Resource) => {+export const getExportResourceExtension = (resource: Resource) => {const filenameExtension = resource.filename?.match(/\.([a-z0-9]{1,12})$/i)?.[1];if (filenameExtension) {return filenameExtension.toLowerCase();@@ -121,7 +121,7 @@ const getExtension = (resource: Resource) => {const encodeRelativePath = (path: string) => path.split("/").map(encodeURIComponent).join("/");-const replaceResourceUrl = (markdown: string, resourceUrl: string, relativePath: string) => {+export const replaceExportResourceUrl = (markdown: string, resourceUrl: string, relativePath: string) => {const encodedPath = encodeRelativePath(relativePath);const absoluteUrl = typeof window === "undefined" ? null : new URL(resourceUrl, window.location.origin).toString();let result = markdown.split(resourceUrl).join(encodedPath);@@ -174,7 +174,7 @@ export const createMarkdownExport = async (const notebookPath = notebookPaths.get(memo.notebookId) ?? "Unfiled";const usedMemoNames = memoNamesByNotebook.get(notebookPath) ?? new Set<string>();memoNamesByNotebook.set(notebookPath, usedMemoNames);- const memoStem = uniqueName(+ const memoStem = uniqueExportName(sanitizeExportPathSegment(memo.title?.trim() || "Untitled note", "Untitled note"),usedMemoNames);@@ -183,8 +183,8 @@ export const createMarkdownExport = async (let markdown = memo.contentMarkdown;for (const resource of resourcesByMemo.get(memo.id) ?? []) {- const fallbackName = `${resource.kind}-${resource.id}.${getExtension(resource)}`;- const resourceName = uniqueName(+ const fallbackName = `${resource.kind}-${resource.id}.${getExportResourceExtension(resource)}`;+ const resourceName = uniqueExportName(sanitizeExportPathSegment(resource.filename || fallbackName, fallbackName),usedResourceNames);@@ -193,7 +193,7 @@ export const createMarkdownExport = async (const file = new ZipPassThrough(`${notebookPath}/${relativePath}`);zip.add(file);file.push(new Uint8Array(await blob.arrayBuffer()), true);- markdown = replaceResourceUrl(markdown, resource.url, relativePath);+ markdown = replaceExportResourceUrl(markdown, resource.url, relativePath);}const markdownFile = new ZipDeflate(`${notebookPath}/${memoStem}.md`, { level: 6 });diff --git a/docs/openapi.json b/docs/openapi.jsonindex 714b7bb7..c8ee737e 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -890,6 +890,99 @@}}},+ "/api/v1/backups/json": {+ "get": {+ "summary": "Read a page of EdgeEver ZIP recovery data",+ "description": "Returns active memo details, revision history, and resource metadata for browser-side EdgeEver ZIP generation. The resulting archive also contains human-readable Markdown. Trash is excluded.",+ "parameters": [+ { "name": "offset", "in": "query", "schema": { "type": "integer", "minimum": 0, "default": 0 } },+ { "name": "limit", "in": "query", "schema": { "type": "integer", "minimum": 1, "maximum": 50, "default": 25 } }+ ],+ "responses": {+ "200": {+ "description": "A page of logical backup data",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "memos": { "type": "array", "items": { "$ref": "#/components/schemas/MemoDetail" } },+ "resources": { "type": "array", "items": { "$ref": "#/components/schemas/Resource" } },+ "revisions": { "type": "array", "items": { "type": "object", "additionalProperties": true } },+ "totalCount": { "type": "integer" },+ "nextOffset": { "type": ["integer", "null"] }+ },+ "required": ["memos", "resources", "revisions", "totalCount", "nextOffset"]+ }+ }+ }+ }+ }+ }+ },+ "/api/v1/restores/json/notebooks": {+ "post": {+ "summary": "Import a batch of notebooks from an EdgeEver ZIP",+ "description": "Interactive-user-only merge restore. Matching EdgeEver notebook IDs are overwritten.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": { "notebooks": { "type": "array", "minItems": 1, "maxItems": 100, "items": { "type": "object", "additionalProperties": true } } },+ "required": ["notebooks"]+ }+ }+ }+ },+ "responses": { "200": { "$ref": "#/components/responses/Ok" } }+ }+ },+ "/api/v1/restores/json/memos": {+ "post": {+ "summary": "Import a batch of memos from an EdgeEver ZIP",+ "description": "Interactive-user-only merge restore, including current content and revision history. Matching EdgeEver memo IDs are overwritten.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": { "memos": { "type": "array", "minItems": 1, "maxItems": 10, "items": { "type": "object", "additionalProperties": true } } },+ "required": ["memos"]+ }+ }+ }+ },+ "responses": { "200": { "$ref": "#/components/responses/Ok" } }+ }+ },+ "/api/v1/restores/json/resources/{id}": {+ "parameters": [+ { "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }+ ],+ "put": {+ "summary": "Import one resource from an EdgeEver ZIP",+ "description": "Interactive-user-only resource import. The multipart metadata field contains the structured EdgeEver ZIP resource record.",+ "requestBody": {+ "required": true,+ "content": {+ "multipart/form-data": {+ "schema": {+ "type": "object",+ "properties": {+ "metadata": { "type": "string" },+ "file": { "type": "string", "format": "binary" }+ },+ "required": ["metadata", "file"]+ }+ }+ }+ },+ "responses": { "200": { "$ref": "#/components/responses/Ok" } }+ }+ },"/api/v1/resources": {"get": {"summary": "List resources and storage summary",diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex f02a723c..69e3ab9a 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -2,6 +2,9 @@ import type {ApiToken,AuthSession,CreatedApiToken,+ JsonBackupMemo,+ JsonBackupNotebook,+ JsonBackupRevision,MemoDetail,MemoEditSession,MemoRevision,@@ -71,6 +74,10 @@ export type MarkdownExportPage = {nextOffset: number | null;};+export type JsonBackupPage = MarkdownExportPage & {+ revisions: JsonBackupRevision[];+};+export class ApiRequestError extends Error {status: number;code?: string;@@ -284,6 +291,31 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {getMarkdownExportPage: (offset = 0, limit = 50) =>request<MarkdownExportPage>(`/api/v1/exports/markdown?offset=${offset}&limit=${limit}`),+ getJsonBackupPage: (offset = 0, limit = 25) =>+ request<JsonBackupPage>(`/api/v1/backups/json?offset=${offset}&limit=${limit}`),++ restoreJsonNotebooks: (notebooks: JsonBackupNotebook[]) =>+ request<{ ok: true }>("/api/v1/restores/json/notebooks", {+ method: "POST",+ body: JSON.stringify({ notebooks }),+ }),++ restoreJsonMemos: (memos: JsonBackupMemo[]) =>+ request<{ ok: true }>("/api/v1/restores/json/memos", {+ method: "POST",+ body: JSON.stringify({ memos }),+ }),++ restoreJsonResource: (resourceId: string, metadata: JsonBackupMemo["resources"][number], file: Blob) => {+ const form = new FormData();+ form.append("metadata", JSON.stringify(metadata));+ form.append("file", file, metadata.filename || metadata.id);+ return request<{ ok: true }>(`/api/v1/restores/json/resources/${encodeURIComponent(resourceId)}`, {+ method: "PUT",+ body: form,+ });+ },+getResourceBlob: async (resourceUrl: string) => {const headers = new Headers();diff --git a/packages/shared/src/backup.ts b/packages/shared/src/backup.tsnew file mode 100644index 00000000..6428972e--- /dev/null+++ b/packages/shared/src/backup.ts@@ -0,0 +1,144 @@+import { z } from "zod";+import type { TiptapDoc } from "./content";+import type { MemoDetail, Notebook, Resource } from "./types";++export const EDGEEVER_ZIP_FORMAT = "edgeever-zip";+export const EDGEEVER_ZIP_FORMAT_VERSION = 1;++export type JsonBackupManifest = {+ format: typeof EDGEEVER_ZIP_FORMAT;+ formatVersion: typeof EDGEEVER_ZIP_FORMAT_VERSION;+ schemaVersion: number;+ edgeeverVersion: string;+ buildId: string;+ exportedAt: string;+ includesTrash: false;+ counts: {+ notebooks: number;+ memos: number;+ revisions: number;+ resources: number;+ };+};++export type JsonBackupNotebook = Omit<Notebook, "memoCount" | "lastMemoUpdatedAt">;++export type JsonBackupRevision = {+ id: string;+ memoId: string;+ revision: number;+ title: string | null;+ tags: string[];+ contentJson: TiptapDoc;+ contentMarkdown: string;+ contentText: string;+ contentHash: string;+ createdBy: string;+ createdAt: string;+};++export type JsonBackupResource = Omit<Resource, "url"> & {+ archivePath: string;+};++export type JsonBackupMemo = {+ memo: MemoDetail;+ revisions: JsonBackupRevision[];+ resources: JsonBackupResource[];+};++const DateTimeSchema = z.string().datetime();++export const JsonBackupManifestSchema = z.object({+ format: z.literal(EDGEEVER_ZIP_FORMAT),+ formatVersion: z.literal(EDGEEVER_ZIP_FORMAT_VERSION),+ schemaVersion: z.number().int().positive(),+ edgeeverVersion: z.string().trim().min(1),+ buildId: z.string().trim().min(1),+ exportedAt: DateTimeSchema,+ includesTrash: z.literal(false),+ counts: z.object({+ notebooks: z.number().int().min(0),+ memos: z.number().int().min(0),+ revisions: z.number().int().min(0),+ resources: z.number().int().min(0),+ }),+});++export const JsonBackupNotebookSchema = z.object({+ id: z.string().trim().min(1),+ parentId: z.string().trim().min(1).nullable(),+ name: z.string().trim().min(1).max(80),+ slug: z.string().nullable(),+ icon: z.string().nullable(),+ color: z.string().nullable(),+ sortOrder: z.number().int(),+ createdAt: DateTimeSchema,+ updatedAt: DateTimeSchema,+});++const JsonBackupRevisionSchema = z.object({+ id: z.string().trim().min(1),+ memoId: z.string().trim().min(1),+ revision: z.number().int().min(0),+ title: z.string().nullable(),+ tags: z.array(z.string()),+ contentJson: z.unknown(),+ contentMarkdown: z.string(),+ contentText: z.string(),+ contentHash: z.string(),+ createdBy: z.string(),+ createdAt: DateTimeSchema,+});++const MemoDetailSchema = z.object({+ id: z.string().trim().min(1),+ notebookId: z.string().trim().min(1),+ title: z.string().nullable(),+ excerpt: z.string(),+ tags: z.array(z.string()),+ isPinned: z.boolean(),+ isArchived: z.boolean(),+ isDeleted: z.boolean(),+ revision: z.number().int().min(0),+ createdAt: DateTimeSchema,+ updatedAt: DateTimeSchema,+ deletedAt: DateTimeSchema.nullable(),+ contentJson: z.unknown(),+ contentMarkdown: z.string(),+ contentText: z.string(),+ contentHash: z.string(),+ sourceMemoIds: z.array(z.string()),+ mergeSourceCount: z.number().int().min(0),+ mergedIntoMemoId: z.string().nullable(),+});++export const JsonBackupMemoSchema = z.object({+ memo: MemoDetailSchema,+ revisions: z.array(JsonBackupRevisionSchema),+ resources: z.array(z.object({+ id: z.string().trim().min(1),+ memoId: z.string().trim().min(1),+ originalMemoId: z.string().nullable(),+ kind: z.enum(["image", "attachment"]),+ mimeType: z.string().nullable(),+ filename: z.string().nullable(),+ byteSize: z.number().int().min(0),+ sha256: z.string().nullable(),+ width: z.number().int().positive().nullable(),+ height: z.number().int().positive().nullable(),+ createdAt: DateTimeSchema,+ updatedAt: DateTimeSchema,+ archivePath: z.string().trim().min(1),+ })),+});++export const RestoreJsonNotebooksSchema = z.object({+ notebooks: z.array(JsonBackupNotebookSchema).min(1).max(100),+});++export const RestoreJsonMemosSchema = z.object({+ memos: z.array(JsonBackupMemoSchema).min(1).max(10),+});++export const JsonBackupResourceMetadataSchema = JsonBackupMemoSchema.shape.resources.element;diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex 09b3d6be..977d2f02 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -1,4 +1,5 @@export * from "./content";+export * from "./backup";export * from "./memo-safety";export * from "./schemas";export * from "./types";diff --git a/tests/json-backup.test.ts b/tests/json-backup.test.tsnew file mode 100644index 00000000..b7b4601f--- /dev/null+++ b/tests/json-backup.test.ts@@ -0,0 +1,144 @@+import { describe, expect, test } from "bun:test";+import type { JsonBackupMemo, JsonBackupNotebook, MemoDetail, Notebook, Resource } from "@edgeever/shared";+import { strFromU8 } from "fflate";+import { createEdgeEverZip, parseEdgeEverZip, restoreEdgeEverZip } from "../apps/web/src/lib/json-backup";++const notebook = (id: string, name: string, parentId: string | null = null): Notebook => ({+ id,+ parentId,+ name,+ slug: id,+ icon: "notebook",+ color: null,+ sortOrder: parentId ? 20 : 10,+ memoCount: 1,+ lastMemoUpdatedAt: "2026-07-14T00:00:00.000Z",+ createdAt: "2026-07-13T00:00:00.000Z",+ updatedAt: "2026-07-14T00:00:00.000Z",+});++const memo: MemoDetail = {+ id: "memo_backup",+ notebookId: "nb_child",+ title: "Backup note",+ excerpt: "Hello",+ tags: ["backup"],+ isPinned: false,+ isArchived: false,+ isDeleted: false,+ revision: 1,+ createdAt: "2026-07-13T00:00:00.000Z",+ updatedAt: "2026-07-14T00:00:00.000Z",+ deletedAt: null,+ contentJson: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Hello" }] }] },+ contentMarkdown: "Hello\n\n",+ contentText: "Hello",+ contentHash: "hash",+ sourceMemoIds: [],+ mergeSourceCount: 0,+ mergedIntoMemoId: null,+};++const resource: Resource = {+ id: "res_backup",+ memoId: memo.id,+ originalMemoId: null,+ kind: "image",+ mimeType: "image/png",+ filename: "asset.png",+ byteSize: 3,+ sha256: "sha",+ width: 10,+ height: 10,+ createdAt: memo.createdAt,+ updatedAt: memo.updatedAt,+ url: "/api/v1/resources/res_backup/blob",+};++describe("EdgeEver ZIP", () => {+ test("combines readable Markdown with versioned recovery data", async () => {+ const blob = await createEdgeEverZip(+ {+ listNotebooks: async () => ({ notebooks: [notebook("nb_child", "Child", "nb_root"), notebook("nb_root", "Root")] }),+ getPage: async () => ({+ memos: [memo],+ resources: [resource],+ revisions: [{+ id: "rev_backup",+ memoId: memo.id,+ revision: 0,+ title: memo.title,+ tags: memo.tags,+ contentJson: memo.contentJson,+ contentMarkdown: "Hello",+ contentText: "Hello",+ contentHash: "old-hash",+ createdBy: "user",+ createdAt: memo.createdAt,+ }],+ totalCount: 1,+ nextOffset: null,+ }),+ getResourceBlob: async () => new Blob([new Uint8Array([1, 2, 3])], { type: "image/png" }),+ },+ { edgeeverVersion: "0.1.13", buildId: "test-build" }+ );+ const backup = await parseEdgeEverZip(blob);++ expect(backup.manifest.format).toBe("edgeever-zip");+ expect(backup.manifest.formatVersion).toBe(1);+ expect(backup.manifest.counts).toEqual({ notebooks: 2, memos: 1, revisions: 1, resources: 1 });+ expect(backup.notebooks.map((item) => item.id)).toEqual(["nb_root", "nb_child"]);+ expect(backup.memos[0].memo.contentMarkdown).toBe(memo.contentMarkdown);+ expect(Array.from(backup.files[backup.memos[0].resources[0].archivePath])).toEqual([1, 2, 3]);+ const markdown = strFromU8(backup.files["notes/Root/Child/Backup note.md"]);+ expect(markdown).toContain("edgeever_id: \"memo_backup\"");+ expect(markdown).toContain("");+ expect(backup.memos[0].resources[0].archivePath).toBe("notes/Root/Child/Backup note.assets/asset.png");+ });++ test("restores notebooks before memos and binary resources", async () => {+ const calls: string[] = [];+ const { url: _url, ...resourceMetadata } = resource;+ const backupMemo: JsonBackupMemo = {+ memo,+ revisions: [],+ resources: [{ ...resourceMetadata, archivePath: "resources/res_backup/asset.png" }],+ };+ const backup = {+ manifest: {+ format: "edgeever-zip" as const,+ formatVersion: 1 as const,+ schemaVersion: 1,+ edgeeverVersion: "0.1.13",+ buildId: "test-build",+ exportedAt: "2026-07-14T00:00:00.000Z",+ includesTrash: false as const,+ counts: { notebooks: 1, memos: 1, revisions: 0, resources: 1 },+ },+ notebooks: [{+ id: "nb_child",+ parentId: null,+ name: "Child",+ slug: null,+ icon: null,+ color: null,+ sortOrder: 0,+ createdAt: memo.createdAt,+ updatedAt: memo.updatedAt,+ }] satisfies JsonBackupNotebook[],+ memos: [backupMemo],+ files: { "resources/res_backup/asset.png": new Uint8Array([1, 2, 3]) },+ };++ await restoreEdgeEverZip(backup, {+ restoreNotebooks: async () => { calls.push("notebooks"); },+ restoreMemos: async () => { calls.push("memos"); },+ restoreResource: async (_id, _metadata, file) => {+ calls.push(`resource:${file.size}`);+ },+ });++ expect(calls).toEqual(["notebooks", "memos", "resource:3"]);+ });+});