Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

feat: improve organization mcp and cli workflows

tianma8ab55b7cae29
diff --git a/README.md b/README.md
index 44bfab95..5864a4ed 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
>
> **EdgeEver:基于 Cloudflare 全家桶自托管的开源『印象笔记』。**
-EdgeEver 是一个开源、自托管、Cloudflare-native 的现代笔记工作区。它保留经典印象笔记的三栏体验,同时提供清晰的数据模型、REST API,并为未来 MCP/CLI 接入预留接口。
+EdgeEver 是一个开源、自托管、Cloudflare-native 的现代笔记工作区。它保留经典印象笔记的三栏体验,同时提供清晰的数据模型、REST API、MCP endpoint 和本地 CLI。
<p align="center">
<a href="https://deploy.workers.cloudflare.com/?url=https://github.com/msh01/edgeever">
@@ -29,9 +29,10 @@ EdgeEver 是一个开源、自托管、Cloudflare-native 的现代笔记工作
- 图片自动压缩,GIF 会尝试转 animated WebP。
- 附件入口,可查看资源列表和总存储占用。
- 多选合并笔记,原笔记软删除,资源关联迁移到新笔记。
+- 多选移动笔记,笔记本支持拖拽排序和调整层级。
- PWA 可安装,支持静态应用壳离线打开和自动更新。
- 单用户登录,密码使用 PBKDF2-SHA256 hash。
-- REST API-first,后续可接 MCP 和 CLI。
+- REST API-first,支持 API Token、MCP 和 CLI。
## 技术栈
@@ -102,3 +103,20 @@ content_json TipTap/ProseMirror 文档,编辑器权威格式
content_markdown API、Agent、导入导出使用
content_text 搜索、摘要和索引使用
```
+
+## Agent / CLI
+
+在设置里创建 API Token 后,可以给 MCP 或 CLI 使用:
+
+```sh
+bun run cli -- profile set local --url https://你的域名 --token <api-token>
+bun run cli -- --profile local search edgeever
+bun run cli -- --profile local create --notebook nb_inbox --title Hello --body "来自 CLI"
+```
+
+MCP endpoint:
+
+```text
+https://你的域名/mcp
+Authorization: Bearer <api-token>
+```
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index bcdfa9f4..3526f795 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -9,6 +9,7 @@ import {
MemoCreateSchema,
MemoUpdateSchema,
MergeMemosSchema,
+ MoveMemosSchema,
normalizeTags,
TagRenameSchema,
NotebookCreateSchema,
@@ -470,27 +471,17 @@ app.patch("/api/v1/notebooks/:id", zValidator("json", NotebookUpdateSchema), asy
const id = c.req.param("id");
const input = c.req.valid("json");
const actor = getAuditActor(c);
- const current = await getNotebook(c.env.DB, id);
- if (!current) {
- return notFound(c, "Notebook not found");
- }
-
- const nextName = input.name ?? current.name;
- const nextParentId = input.parentId === undefined ? current.parentId : input.parentId;
- const nextSortOrder = input.sortOrder ?? current.sortOrder;
- const now = isoNow();
-
- await c.env.DB.prepare(
- `UPDATE notebooks
- SET name = ?, slug = ?, parent_id = ?, sort_order = ?, updated_at = ?
- WHERE id = ? AND is_deleted = 0`
- )
- .bind(nextName, slugify(nextName), nextParentId ?? null, nextSortOrder, now, id)
- .run();
+ try {
+ const notebook = await updateNotebookRecord(c.env.DB, id, input, actor);
+ return c.json({ notebook });
+ } catch (error) {
+ if (error instanceof AppError) {
+ return apiError(c, error.code, error.message, error.status);
+ }
- await audit(c.env.DB, actor.actorType, actor.actorId, "notebook.update", "notebook", id, input);
- return c.json({ notebook: await getNotebook(c.env.DB, id) });
+ throw error;
+ }
});
app.delete("/api/v1/notebooks/:id", async (c) => {
@@ -693,6 +684,36 @@ app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {
return c.json({ memo: await getMemoDetail(c.env.DB, id) }, 201);
});
+app.post("/api/v1/memos/batch/move", zValidator("json", MoveMemosSchema), async (c) => {
+ const denied = requireScopes(c, "write:memos");
+
+ if (denied) {
+ return denied;
+ }
+
+ const input = c.req.valid("json");
+ const target = await getNotebook(c.env.DB, input.notebookId);
+
+ if (!target) {
+ return notFound(c, "Target notebook not found");
+ }
+
+ const actor = getAuditActor(c);
+ const actorLabel = getActorLabel(c);
+
+ try {
+ const moved = await moveMemosToNotebook(c.env.DB, input.memoIds, input.notebookId, actor, actorLabel);
+
+ return c.json({ ok: true, moved });
+ } catch (error) {
+ if (error instanceof AppError) {
+ return apiError(c, error.code, error.message, error.status);
+ }
+
+ throw error;
+ }
+});
+
app.get("/api/v1/memos/:id", async (c) => {
const denied = requireScopes(c, "read:memos");
@@ -1150,93 +1171,17 @@ app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (c)
const input = c.req.valid("json");
const actor = getAuditActor(c);
const actorLabel = getActorLabel(c);
- const uniqueMemoIds = Array.from(new Set(input.memoIds));
- const placeholders = uniqueMemoIds.map(() => "?").join(", ");
- const rows = await 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, c.revision,
- c.content_json, c.content_markdown, c.content_text, c.content_hash,
- m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id
- FROM memos m
- INNER JOIN memo_contents c ON c.memo_id = m.id
- WHERE m.is_deleted = 0 AND m.id IN (${placeholders})`
- )
- .bind(...uniqueMemoIds)
- .all<MemoDetailRow>();
-
- if (rows.results.length !== uniqueMemoIds.length) {
- return c.json(
- {
- error: {
- code: "missing_memos",
- message: "One or more memos cannot be merged.",
- },
- },
- 400
- );
- }
-
- const ordered = uniqueMemoIds
- .map((memoId) => rows.results.find((row) => row.id === memoId))
- .filter((row): row is MemoDetailRow => Boolean(row));
- const notebookId = input.notebookId ?? ordered[0].notebook_id;
- const title = input.title || `合并笔记 ${new Date().toLocaleDateString("zh-CN")}`;
- const mergedMarkdown = ordered.map((memo) => memo.content_markdown).join("\n\n---\n\n");
- const contentJson = markdownToDoc(mergedMarkdown);
- const contentText = docToText(contentJson);
- const tags = Array.from(new Set(ordered.flatMap((memo) => parseJsonArray(memo.tags_json))));
- const excerpt = createExcerpt(contentText || title);
- const contentHash = await sha256(mergedMarkdown + JSON.stringify(contentJson));
- const newMemoId = createId("memo");
- const now = isoNow();
- await c.env.DB.batch([
- c.env.DB.prepare(
- `INSERT INTO memos (
- id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count,
- created_by, updated_by, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
- ).bind(
- newMemoId,
- notebookId,
- title,
- excerpt,
- JSON.stringify(tags),
- JSON.stringify(uniqueMemoIds),
- uniqueMemoIds.length,
- actorLabel,
- actorLabel,
- now,
- now
- ),
- c.env.DB.prepare(
- `INSERT INTO memo_contents (
- memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at
- ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`
- ).bind(newMemoId, JSON.stringify(contentJson), mergedMarkdown, contentText, contentHash, now, now),
- c.env.DB.prepare(
- `INSERT INTO memos_fts (memo_id, title, content_text, tags)
- VALUES (?, ?, ?, ?)`
- ).bind(newMemoId, title, contentText, tags.join(" ")),
- c.env.DB.prepare(
- `UPDATE memos
- SET is_deleted = 1, deleted_at = ?, merged_into_memo_id = ?, merged_at = ?, updated_at = ?
- WHERE id IN (${placeholders})`
- ).bind(now, newMemoId, now, now, ...uniqueMemoIds),
- c.env.DB.prepare(`DELETE FROM memos_fts WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),
- c.env.DB.prepare(
- `UPDATE resources
- SET original_memo_id = COALESCE(original_memo_id, memo_id),
- memo_id = ?,
- updated_at = ?
- WHERE memo_id IN (${placeholders})`
- ).bind(newMemoId, now, ...uniqueMemoIds),
- auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.merge", "memo", newMemoId, {
- sourceMemoIds: uniqueMemoIds,
- }),
- ]);
+ try {
+ const memo = await mergeMemosRecord(c.env.DB, input, actor, actorLabel);
+ return c.json({ memo }, 201);
+ } catch (error) {
+ if (error instanceof AppError) {
+ return apiError(c, error.code, error.message, error.status);
+ }
- return c.json({ memo: await getMemoDetail(c.env.DB, newMemoId) }, 201);
+ throw error;
+ }
});
app.get("/mcp", (c) =>
@@ -1250,112 +1195,214 @@ app.get("/mcp", (c) =>
);
app.post("/mcp", async (c) => {
- let request: JsonRpcRequest;
+ let payload: unknown;
try {
- request = (await c.req.json()) as JsonRpcRequest;
+ payload = await c.req.json();
} catch {
return c.json(jsonRpcError(null, -32700, "Parse error"), 400);
}
- if (!request || request.jsonrpc !== "2.0" || typeof request.method !== "string") {
- return c.json(jsonRpcError(getJsonRpcId(request), -32600, "Invalid Request"), 400);
+ if (Array.isArray(payload)) {
+ if (payload.length === 0) {
+ return c.json(jsonRpcError(null, -32600, "Invalid Request"), 400);
+ }
+
+ const results = await Promise.all(payload.map((request) => handleMcpMessage(c, request)));
+ const responses = results.filter((result): result is JsonRpcHandlerResult => Boolean(result));
+ const bodies = responses.map((response) => response.body);
+
+ if (bodies.length === 0) {
+ return new Response(null, { status: 204 });
+ }
+
+ return c.json(bodies, Math.max(...responses.map((response) => response.status)) as 200);
}
- if (request.method === "notifications/initialized" && request.id === undefined) {
+ const result = await handleMcpMessage(c, payload);
+
+ if (!result) {
return new Response(null, { status: 204 });
}
+ return c.json(result.body, result.status as 200);
+});
+
+app.notFound((c) =>
+ c.json(
+ {
+ error: {
+ code: "not_found",
+ message: "Route not found",
+ },
+ },
+ 404
+ )
+);
+
+export default app;
+
+type JsonRpcRequest = {
+ jsonrpc?: string;
+ id?: string | number | null;
+ method?: string;
+ params?: unknown;
+};
+
+type JsonRpcId = string | number | null;
+type JsonRpcHandlerResult = {
+ body: unknown;
+ status: number;
+};
+
+class AppError extends Error {
+ code: string;
+ status: number;
+
+ constructor(code: string, message: string, status = 400) {
+ super(message);
+ this.name = "AppError";
+ this.code = code;
+ this.status = status;
+ }
+}
+
+const MCP_PROTOCOL_VERSION = "2024-11-05";
+
+const handleMcpMessage = async (c: AppContext, payload: unknown): Promise<JsonRpcHandlerResult | null> => {
+ const request = payload as JsonRpcRequest;
+ const id = getJsonRpcId(payload);
+ const isNotification =
+ payload &&
+ typeof payload === "object" &&
+ !("id" in payload) &&
+ typeof (payload as JsonRpcRequest).method === "string";
+
+ if (!request || request.jsonrpc !== "2.0" || typeof request.method !== "string") {
+ return { body: jsonRpcError(id, -32600, "Invalid Request"), status: 400 };
+ }
+
+ if (request.method === "notifications/initialized" && isNotification) {
+ return null;
+ }
+
if (request.method === "initialize") {
- return c.json(
- jsonRpcResult(request.id ?? null, {
- protocolVersion: "2024-11-05",
+ return {
+ body: jsonRpcResult(request.id ?? null, {
+ protocolVersion: MCP_PROTOCOL_VERSION,
capabilities: {
- tools: {},
+ tools: {
+ listChanged: false,
+ },
},
serverInfo: {
name: "edgeever",
version: "0.1.0",
},
- })
- );
+ instructions:
+ "Use scoped EdgeEver API tokens. Prefer read-only scopes for search/list/get tools and grant write scopes only to agents that modify notes.",
+ }),
+ status: 200,
+ };
}
const auth = await authenticateRequest(c, true);
if (!auth) {
- return c.json(jsonRpcError(request.id ?? null, -32001, "Authentication required"), 401);
+ return { body: jsonRpcError(request.id ?? null, -32001, "Authentication required"), status: 401 };
}
c.set("auth", auth);
if (request.method === "tools/list") {
- return c.json(
- jsonRpcResult(request.id ?? null, {
+ return {
+ body: jsonRpcResult(request.id ?? null, {
tools: MCP_TOOLS,
- })
- );
+ }),
+ status: 200,
+ };
}
if (request.method === "tools/call") {
const params = asRecord(request.params);
- const name = typeof params.name === "string" ? params.name : "";
- const args = asRecord(params.arguments);
+ const name = getOptionalString(params.name);
+
+ if (!name) {
+ return { body: jsonRpcError(request.id ?? null, -32602, "Tool name is required"), status: 400 };
+ }
try {
- const result = await callMcpTool(c, auth, name, args);
- return c.json(
- jsonRpcResult(request.id ?? null, {
+ const result = await callMcpTool(c, auth, name, asRecord(params.arguments));
+ return {
+ body: jsonRpcResult(request.id ?? null, {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
- })
- );
+ isError: false,
+ }),
+ status: 200,
+ };
} catch (error) {
- const message = error instanceof Error ? error.message : "Tool call failed";
- return c.json(jsonRpcError(request.id ?? null, -32000, message), 400);
+ const mapped = mapMcpToolError(error);
+ return {
+ body: jsonRpcError(request.id ?? null, mapped.rpcCode, mapped.message, mapped.data),
+ status: mapped.status,
+ };
}
}
- return c.json(jsonRpcError(request.id ?? null, -32601, "Method not found"), 404);
-});
+ if (isNotification) {
+ return null;
+ }
-app.notFound((c) =>
- c.json(
- {
- error: {
- code: "not_found",
- message: "Route not found",
- },
- },
- 404
- )
-);
+ return { body: jsonRpcError(request.id ?? null, -32601, "Method not found"), status: 404 };
+};
-export default app;
+const mapMcpToolError = (error: unknown) => {
+ if (error instanceof AppError) {
+ const rpcCode =
+ error.status === 401
+ ? -32001
+ : error.status === 403
+ ? -32003
+ : error.status === 404
+ ? -32004
+ : error.status === 409
+ ? -32009
+ : -32602;
+
+ return {
+ rpcCode,
+ status: error.status,
+ message: error.message,
+ data: {
+ code: error.code,
+ },
+ };
+ }
-type JsonRpcRequest = {
- jsonrpc?: string;
- id?: string | number | null;
- method?: string;
- params?: unknown;
+ return {
+ rpcCode: -32000,
+ status: 400,
+ message: error instanceof Error ? error.message : "Tool call failed",
+ data: undefined,
+ };
};
-type JsonRpcId = string | number | null;
-
const MCP_TOOLS = [
{
name: "search_memos",
description: "Search active EdgeEver memos by text, tag, or notebook.",
inputSchema: {
type: "object",
+ additionalProperties: false,
properties: {
query: { type: "string" },
notebookId: { type: "string" },
- limit: { type: "number", minimum: 1, maximum: 50 },
+ limit: { type: "integer", minimum: 1, maximum: 50 },
},
},
},
@@ -1365,6 +1412,7 @@ const MCP_TOOLS = [
inputSchema: {
type: "object",
required: ["memoId"],
+ additionalProperties: false,
properties: {
memoId: { type: "string" },
},
@@ -1376,6 +1424,7 @@ const MCP_TOOLS = [
inputSchema: {
type: "object",
required: ["notebookId"],
+ additionalProperties: false,
properties: {
notebookId: { type: "string" },
title: { type: "string" },
@@ -1390,13 +1439,55 @@ const MCP_TOOLS = [
inputSchema: {
type: "object",
required: ["memoId"],
+ additionalProperties: false,
properties: {
memoId: { type: "string" },
title: { type: "string" },
contentMarkdown: { type: "string" },
tags: { type: "array", items: { type: "string" } },
notebookId: { type: "string" },
- expectedRevision: { type: "number" },
+ expectedRevision: { type: "integer", minimum: 0 },
+ },
+ },
+ },
+ {
+ name: "move_memos",
+ description: "Move one or more active memos to another notebook.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds", "notebookId"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 1, maxItems: 100, items: { type: "string" } },
+ notebookId: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "merge_memos",
+ description: "Merge multiple active memos into a new memo and soft-delete the sources.",
+ inputSchema: {
+ type: "object",
+ required: ["memoIds"],
+ additionalProperties: false,
+ properties: {
+ memoIds: { type: "array", minItems: 2, maxItems: 50, items: { type: "string" } },
+ notebookId: { type: "string" },
+ title: { type: "string" },
+ },
+ },
+ },
+ {
+ name: "move_notebook",
+ description: "Move a notebook under another notebook or root and update its sort order.",
+ inputSchema: {
+ type: "object",
+ required: ["notebookId"],
+ additionalProperties: false,
+ properties: {
+ notebookId: { type: "string" },
+ parentId: { type: ["string", "null"] },
+ sortOrder: { type: "integer" },
},
},
},
@@ -1405,6 +1496,7 @@ const MCP_TOOLS = [
description: "List active notebooks.",
inputSchema: {
type: "object",
+ additionalProperties: false,
properties: {},
},
},
@@ -1413,6 +1505,7 @@ const MCP_TOOLS = [
description: "List tags and memo counts.",
inputSchema: {
type: "object",
+ additionalProperties: false,
properties: {},
},
},
@@ -1488,6 +1581,54 @@ const callMcpTool = async (
return { memo: result.memo };
}
+ case "move_memos": {
+ assertScope(auth, "write:memos");
+ const notebookId = getRequiredString(args.notebookId, "notebookId");
+ const memoIds = getRequiredStringArray(args.memoIds, "memoIds");
+ const target = await getNotebook(c.env.DB, notebookId);
+
+ if (!target) {
+ throw new AppError("not_found", "Target notebook not found", 404);
+ }
+
+ const actor = getAuditActor(c);
+ const actorLabel = getActorLabel(c);
+ const moved = await moveMemosToNotebook(c.env.DB, memoIds, notebookId, actor, actorLabel);
+
+ return { ok: true, moved };
+ }
+ case "merge_memos": {
+ assertScope(auth, "write:memos");
+ const actor = getAuditActor(c);
+ const actorLabel = getActorLabel(c);
+ const memo = await mergeMemosRecord(
+ c.env.DB,
+ {
+ memoIds: getRequiredStringArray(args.memoIds, "memoIds"),
+ notebookId: getOptionalString(args.notebookId) ?? undefined,
+ title: getOptionalString(args.title) ?? undefined,
+ },
+ actor,
+ actorLabel
+ );
+
+ return { memo };
+ }
+ case "move_notebook": {
+ assertScope(auth, "write:notebooks");
+ const actor = getAuditActor(c);
+ const notebook = await updateNotebookRecord(
+ c.env.DB,
+ getRequiredString(args.notebookId, "notebookId"),
+ {
+ parentId: args.parentId === null ? null : getOptionalString(args.parentId) ?? undefined,
+ sortOrder: typeof args.sortOrder === "number" && Number.isInteger(args.sortOrder) ? args.sortOrder : undefined,
+ },
+ actor
+ );
+
+ return { notebook };
+ }
case "list_notebooks": {
assertScope(auth, "read:notebooks");
return { notebooks: await listNotebooks(c.env.DB) };
@@ -1535,7 +1676,7 @@ const getRequiredString = (value: unknown, name: string) => {
const parsed = getOptionalString(value);
if (!parsed) {
- throw new Error(`${name} is required`);
+ throw new AppError("invalid_params", `${name} is required`, 400);
}
return parsed;
@@ -1544,6 +1685,16 @@ const getRequiredString = (value: unknown, name: string) => {
const getOptionalStringArray = (value: unknown) =>
Array.isArray(value) ? value.filter((item): item is string => typeof item === "string") : [];
+const getRequiredStringArray = (value: unknown, name: string) => {
+ const items = getOptionalStringArray(value);
+
+ if (items.length === 0) {
+ throw new AppError("invalid_params", `${name} must include at least one item`, 400);
+ }
+
+ return items;
+};
+
const isAuthRequired = async (env: Bindings) => {
if (env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim()) {
return true;
@@ -1778,7 +1929,7 @@ const requireScopes = (c: AppContext, ...scopes: TokenScope[]) => {
const assertScope = (auth: AuthContext, scope: TokenScope) => {
if (!hasScopes(auth, [scope])) {
- throw new Error(`Missing required scope: ${scope}`);
+ throw new AppError("forbidden", `Missing required scope: ${scope}`, 403);
}
};
@@ -2202,6 +2353,85 @@ const getNotebook = async (db: D1Database, id: string): Promise<Notebook | null>
return row ? mapNotebook(row) : null;
};
+const updateNotebookRecord = async (
+ db: D1Database,
+ id: string,
+ input: { name?: string; parentId?: string | null; sortOrder?: number },
+ actor: { actorType: "user" | "agent"; actorId: string | null }
+) => {
+ const current = await getNotebook(db, id);
+
+ if (!current) {
+ throw new AppError("not_found", "Notebook not found", 404);
+ }
+
+ const nextName = input.name ?? current.name;
+ const nextParentId = input.parentId === undefined ? current.parentId : input.parentId;
+ const nextSortOrder = input.sortOrder ?? current.sortOrder;
+ const now = isoNow();
+
+ if (nextParentId === id) {
+ throw new AppError("bad_request", "Notebook cannot be its own parent", 400);
+ }
+
+ if (nextParentId) {
+ const parent = await getNotebook(db, nextParentId);
+
+ if (!parent) {
+ throw new AppError("not_found", "Parent notebook not found", 404);
+ }
+
+ if (await isNotebookDescendant(db, nextParentId, id)) {
+ throw new AppError("notebook_cycle", "Notebook cannot be moved into its own descendant.", 409);
+ }
+ }
+
+ await db.batch([
+ db
+ .prepare(
+ `UPDATE notebooks
+ SET name = ?, slug = ?, parent_id = ?, sort_order = ?, updated_at = ?
+ WHERE id = ? AND is_deleted = 0`
+ )
+ .bind(nextName, slugify(nextName), nextParentId ?? null, nextSortOrder, now, id),
+ auditStatement(db, actor.actorType, actor.actorId, "notebook.update", "notebook", id, input),
+ ]);
+
+ const notebook = await getNotebook(db, id);
+
+ if (!notebook) {
+ throw new AppError("not_found", "Notebook not found after update", 404);
+ }
+
+ return notebook;
+};
+
+const isNotebookDescendant = async (db: D1Database, candidateId: string, ancestorId: string) => {
+ const row = await db
+ .prepare(
+ `WITH RECURSIVE descendants(id) AS (
+ SELECT id
+ FROM notebooks
+ WHERE parent_id = ? AND is_deleted = 0
+
+ UNION ALL
+
+ SELECT n.id
+ FROM notebooks n
+ INNER JOIN descendants d ON n.parent_id = d.id
+ WHERE n.is_deleted = 0
+ )
+ SELECT id
+ FROM descendants
+ WHERE id = ?
+ LIMIT 1`
+ )
+ .bind(ancestorId, candidateId)
+ .first<{ id: string }>();
+
+ return Boolean(row);
+};
+
const getMemoDetailRow = async (
db: D1Database,
id: string,
@@ -2225,6 +2455,170 @@ const getMemoDetail = async (db: D1Database, id: string, includeDeleted = false)
return row ? mapMemoDetail(row) : null;
};
+const moveMemosToNotebook = async (
+ db: D1Database,
+ memoIds: string[],
+ notebookId: string,
+ actor: { actorType: "user" | "agent"; actorId: string | null },
+ actorLabel: string
+) => {
+ const uniqueMemoIds = Array.from(new Set(memoIds));
+
+ if (uniqueMemoIds.length === 0) {
+ return 0;
+ }
+
+ const placeholders = uniqueMemoIds.map(() => "?").join(", ");
+ const rows = await db
+ .prepare(
+ `SELECT id, notebook_id
+ FROM memos
+ WHERE is_deleted = 0 AND id IN (${placeholders})`
+ )
+ .bind(...uniqueMemoIds)
+ .all<{ id: string; notebook_id: string }>();
+
+ if (rows.results.length !== uniqueMemoIds.length) {
+ throw new AppError("missing_memos", "One or more memos cannot be moved.", 400);
+ }
+
+ const now = isoNow();
+ const statements: D1PreparedStatement[] = [
+ db
+ .prepare(
+ `UPDATE memos
+ SET notebook_id = ?, updated_by = ?, updated_at = ?
+ WHERE is_deleted = 0 AND id IN (${placeholders})`
+ )
+ .bind(notebookId, actorLabel, now, ...uniqueMemoIds),
+ ];
+
+ for (const row of rows.results) {
+ statements.push(
+ auditStatement(db, actor.actorType, actor.actorId, "memo.move", "memo", row.id, {
+ fromNotebookId: row.notebook_id,
+ toNotebookId: notebookId,
+ })
+ );
+ }
+
+ await db.batch(statements);
+ return uniqueMemoIds.length;
+};
+
+const mergeMemosRecord = async (
+ db: D1Database,
+ input: { memoIds: string[]; notebookId?: string; title?: string },
+ actor: { actorType: "user" | "agent"; actorId: string | null },
+ actorLabel: string
+) => {
+ const uniqueMemoIds = Array.from(new Set(input.memoIds));
+
+ if (uniqueMemoIds.length < 2) {
+ throw new AppError("bad_request", "At least two memos are required to merge.", 400);
+ }
+
+ const placeholders = uniqueMemoIds.map(() => "?").join(", ");
+ const rows = await 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, c.revision,
+ c.content_json, c.content_markdown, c.content_text, c.content_hash,
+ m.source_memo_ids, m.merge_source_count, m.merged_into_memo_id
+ FROM memos m
+ INNER JOIN memo_contents c ON c.memo_id = m.id
+ WHERE m.is_deleted = 0 AND m.id IN (${placeholders})`
+ )
+ .bind(...uniqueMemoIds)
+ .all<MemoDetailRow>();
+
+ if (rows.results.length !== uniqueMemoIds.length) {
+ throw new AppError("missing_memos", "One or more memos cannot be merged.", 400);
+ }
+
+ if (input.notebookId && !(await getNotebook(db, input.notebookId))) {
+ throw new AppError("not_found", "Target notebook not found", 404);
+ }
+
+ const ordered = uniqueMemoIds
+ .map((memoId) => rows.results.find((row) => row.id === memoId))
+ .filter((row): row is MemoDetailRow => Boolean(row));
+ const notebookId = input.notebookId ?? ordered[0].notebook_id;
+ const title = input.title || `合并笔记 ${new Date().toLocaleDateString("zh-CN")}`;
+ const mergedMarkdown = ordered.map((memo) => memo.content_markdown).join("\n\n---\n\n");
+ const contentJson = markdownToDoc(mergedMarkdown);
+ const contentText = docToText(contentJson);
+ const tags = Array.from(new Set(ordered.flatMap((memo) => parseJsonArray(memo.tags_json))));
+ const excerpt = createExcerpt(contentText || title);
+ const contentHash = await sha256(mergedMarkdown + JSON.stringify(contentJson));
+ const newMemoId = createId("memo");
+ const now = isoNow();
+
+ await db.batch([
+ db
+ .prepare(
+ `INSERT INTO memos (
+ id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count,
+ created_by, updated_by, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ )
+ .bind(
+ newMemoId,
+ notebookId,
+ title,
+ excerpt,
+ JSON.stringify(tags),
+ JSON.stringify(uniqueMemoIds),
+ uniqueMemoIds.length,
+ actorLabel,
+ actorLabel,
+ now,
+ now
+ ),
+ db
+ .prepare(
+ `INSERT INTO memo_contents (
+ memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at
+ ) VALUES (?, ?, ?, ?, ?, 0, ?, ?)`
+ )
+ .bind(newMemoId, JSON.stringify(contentJson), mergedMarkdown, contentText, contentHash, now, now),
+ db
+ .prepare(
+ `INSERT INTO memos_fts (memo_id, title, content_text, tags)
+ VALUES (?, ?, ?, ?)`
+ )
+ .bind(newMemoId, title, contentText, tags.join(" ")),
+ db
+ .prepare(
+ `UPDATE memos
+ SET is_deleted = 1, deleted_at = ?, merged_into_memo_id = ?, merged_at = ?, updated_at = ?
+ WHERE id IN (${placeholders})`
+ )
+ .bind(now, newMemoId, now, now, ...uniqueMemoIds),
+ db.prepare(`DELETE FROM memos_fts WHERE memo_id IN (${placeholders})`).bind(...uniqueMemoIds),
+ db
+ .prepare(
+ `UPDATE resources
+ SET original_memo_id = COALESCE(original_memo_id, memo_id),
+ memo_id = ?,
+ updated_at = ?
+ WHERE memo_id IN (${placeholders})`
+ )
+ .bind(newMemoId, now, ...uniqueMemoIds),
+ auditStatement(db, actor.actorType, actor.actorId, "memo.merge", "memo", newMemoId, {
+ sourceMemoIds: uniqueMemoIds,
+ }),
+ ]);
+
+ const memo = await getMemoDetail(db, newMemoId);
+
+ if (!memo) {
+ throw new AppError("not_found", "Merged memo not found after create.", 404);
+ }
+
+ return memo;
+};
+
const createMemoRecord = async (
db: D1Database,
input: { notebookId: string; title?: string; contentMarkdown?: string; tags?: string[] },
@@ -2629,6 +3023,17 @@ const badRequest = (c: Context, message: string) =>
400
);
+const apiError = (c: Context, code: string, message: string, status: number) =>
+ c.json(
+ {
+ error: {
+ code,
+ message,
+ },
+ },
+ status as 400
+ );
+
const conflict = (c: Context, code: string, message: string) =>
c.json(
{
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 79c95533..edddca14 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -62,6 +62,7 @@ import {
useMemo,
useRef,
useState,
+ type DragEvent,
type FormEvent,
type MouseEvent,
type ReactNode,
@@ -74,6 +75,7 @@ import { Button } from "@/components/ui/button";
type Pane = "notebooks" | "memos" | "editor";
type MemoView = "notebook" | "trash";
+type NotebookDropPosition = "before" | "inside" | "after";
const IMAGE_COMPRESSION_STORAGE_KEY = "edgeever.imageCompressionEnabled";
@@ -249,8 +251,13 @@ const WorkspaceApp = ({
});
const updateNotebookMutation = useMutation({
- mutationFn: ({ notebookId, name }: { notebookId: string; name: string }) =>
- api.updateNotebook(notebookId, { name }),
+ mutationFn: ({
+ notebookId,
+ payload,
+ }: {
+ notebookId: string;
+ payload: { name?: string; parentId?: string | null; sortOrder?: number };
+ }) => api.updateNotebook(notebookId, payload),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: ["notebooks"] });
},
@@ -291,6 +298,15 @@ const WorkspaceApp = ({
},
});
+ const moveMemosMutation = useMutation({
+ mutationFn: api.moveMemos,
+ onSuccess: async () => {
+ setSelectedMemoIds(new Set());
+ await queryClient.invalidateQueries({ queryKey: ["memos"] });
+ await queryClient.invalidateQueries({ queryKey: ["memo"] });
+ },
+ });
+
const deleteMemoMutation = useMutation({
mutationFn: ({ memoId, permanent }: { memoId: string; permanent?: boolean }) =>
api.deleteMemo(memoId, { permanent }),
@@ -331,7 +347,7 @@ const WorkspaceApp = ({
return;
}
- updateNotebookMutation.mutate({ notebookId: notebook.id, name: name.trim() });
+ updateNotebookMutation.mutate({ notebookId: notebook.id, payload: { name: name.trim() } });
};
const handleDeleteNotebook = (notebook: Notebook) => {
@@ -360,6 +376,41 @@ const WorkspaceApp = ({
});
};
+ const handleMoveNotebook = (
+ notebookId: string,
+ targetNotebookId: string,
+ position: NotebookDropPosition
+ ) => {
+ if (notebookId === targetNotebookId) {
+ return;
+ }
+
+ const target = notebooks.find((notebook) => notebook.id === targetNotebookId);
+
+ if (!target) {
+ return;
+ }
+
+ updateNotebookMutation.mutate({
+ notebookId,
+ payload: {
+ parentId: position === "inside" ? target.id : target.parentId,
+ sortOrder: position === "inside" ? Date.now() : getNotebookDropSortOrder(notebooks, target, position),
+ },
+ });
+ };
+
+ const handleMoveSelectedMemos = (targetNotebookId: string) => {
+ if (selectedMemoIds.size === 0 || memoView === "trash") {
+ return;
+ }
+
+ moveMemosMutation.mutate({
+ memoIds: Array.from(selectedMemoIds),
+ notebookId: targetNotebookId,
+ });
+ };
+
const handleMerge = () => {
if (!selectedNotebookId || selectedMemoIds.size < 2 || memoView === "trash") {
return;
@@ -396,6 +447,7 @@ const WorkspaceApp = ({
onCreateNotebook={handleCreateNotebook}
onRenameNotebook={handleRenameNotebook}
onDeleteNotebook={handleDeleteNotebook}
+ onMoveNotebook={handleMoveNotebook}
onBackToList={() => setActivePane("memos")}
onLogout={onLogout}
isLoggingOut={isLoggingOut}
@@ -421,6 +473,7 @@ const WorkspaceApp = ({
>
<MemoListPane
notebook={selectedNotebook}
+ notebooks={notebooks}
view={memoView}
memos={memos}
selectedMemoId={selectedMemoId}
@@ -429,6 +482,7 @@ const WorkspaceApp = ({
isLoading={memosQuery.isLoading}
isCreating={createMemoMutation.isPending}
isMerging={mergeMutation.isPending}
+ isMoving={moveMemosMutation.isPending}
multiSelectKeyDown={multiSelectKeyDown}
onBackToNotebooks={() => setActivePane("notebooks")}
onSearch={setSearch}
@@ -441,6 +495,7 @@ const WorkspaceApp = ({
setSelectedMemoIds((current) => toggleMemoSelection(current, memoId));
}}
onMerge={handleMerge}
+ onMoveSelectedMemos={handleMoveSelectedMemos}
/>
</section>
@@ -585,6 +640,49 @@ const toggleMemoSelection = (current: Set<string>, memoId: string) => {
return next;
};
+const getNotebookDropPosition = (event: DragEvent<HTMLElement>): NotebookDropPosition => {
+ const rect = event.currentTarget.getBoundingClientRect();
+ const offset = event.clientY - rect.top;
+
+ if (offset < rect.height * 0.28) {
+ return "before";
+ }
+
+ if (offset > rect.height * 0.72) {
+ return "after";
+ }
+
+ return "inside";
+};
+
+const getNotebookDropSortOrder = (
+ notebooks: Notebook[],
+ target: Notebook,
+ position: Exclude<NotebookDropPosition, "inside">
+) => {
+ const siblings = notebooks
+ .filter((notebook) => notebook.parentId === target.parentId)
+ .sort((left, right) => left.sortOrder - right.sortOrder || left.name.localeCompare(right.name));
+ const targetIndex = siblings.findIndex((notebook) => notebook.id === target.id);
+ const insertionIndex = targetIndex < 0 ? siblings.length : position === "before" ? targetIndex : targetIndex + 1;
+ const previous = siblings[insertionIndex - 1];
+ const next = siblings[insertionIndex];
+
+ if (!previous && !next) {
+ return target.sortOrder + (position === "before" ? -1000 : 1000);
+ }
+
+ if (!previous) {
+ return next.sortOrder - 1000;
+ }
+
+ if (!next) {
+ return previous.sortOrder + 1000;
+ }
+
+ return Math.floor((previous.sortOrder + next.sortOrder) / 2);
+};
+
const NotebookPane = ({
authRequired,
user,
@@ -595,6 +693,7 @@ const NotebookPane = ({
onCreateNotebook,
onRenameNotebook,
onDeleteNotebook,
+ onMoveNotebook,
onBackToList,
onLogout,
isLoggingOut,
@@ -614,6 +713,7 @@ const NotebookPane = ({
onCreateNotebook: (parentId?: string | null) => void;
onRenameNotebook: (notebook: Notebook) => void;
onDeleteNotebook: (notebook: Notebook) => void;
+ onMoveNotebook: (notebookId: string, targetNotebookId: string, position: NotebookDropPosition) => void;
onBackToList: () => void;
onLogout: () => void;
isLoggingOut: boolean;
@@ -664,6 +764,7 @@ const NotebookPane = ({
onCreateNotebook={onCreateNotebook}
onRenameNotebook={onRenameNotebook}
onDeleteNotebook={onDeleteNotebook}
+ onMoveNotebook={onMoveNotebook}
/>
))}
</div>
@@ -713,6 +814,7 @@ const NotebookTreeItem = ({
onCreateNotebook,
onRenameNotebook,
onDeleteNotebook,
+ onMoveNotebook,
}: {
node: NotebookNode;
depth: number;
@@ -721,19 +823,54 @@ const NotebookTreeItem = ({
onCreateNotebook: (parentId?: string | null) => void;
onRenameNotebook: (notebook: Notebook) => void;
onDeleteNotebook: (notebook: Notebook) => void;
+ onMoveNotebook: (notebookId: string, targetNotebookId: string, position: NotebookDropPosition) => void;
}) => {
const [open, setOpen] = useState(true);
const hasChildren = node.children.length > 0;
const selected = node.id === selectedNotebookId;
const isInbox = node.slug === "inbox";
+ const [dropPosition, setDropPosition] = useState<NotebookDropPosition | null>(null);
+
+ const handleDragOver = (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "move";
+ setDropPosition(getNotebookDropPosition(event));
+ };
+
+ const handleDrop = (event: DragEvent<HTMLDivElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ const notebookId = event.dataTransfer.getData("application/x-edgeever-notebook");
+ const position = getNotebookDropPosition(event);
+ setDropPosition(null);
+
+ if (!notebookId || notebookId === node.id) {
+ return;
+ }
+
+ onMoveNotebook(notebookId, node.id, position);
+ setOpen(true);
+ };
return (
<div>
<div
className={cn(
"group flex h-9 items-center gap-1 rounded-md px-2 text-sm transition",
- selected ? "border border-emerald-200 bg-emerald-100 text-emerald-950" : "text-slate-700 hover:bg-emerald-50"
+ selected ? "border border-emerald-200 bg-emerald-100 text-emerald-950" : "text-slate-700 hover:bg-emerald-50",
+ dropPosition === "inside" && "ring-2 ring-emerald-300",
+ dropPosition === "before" && "shadow-[inset_0_2px_0_0_#34d399]",
+ dropPosition === "after" && "shadow-[inset_0_-2px_0_0_#34d399]"
)}
+ draggable
+ onDragStart={(event) => {
+ event.dataTransfer.effectAllowed = "move";
+ event.dataTransfer.setData("application/x-edgeever-notebook", node.id);
+ event.dataTransfer.setData("text/plain", node.id);
+ }}
+ onDragOver={handleDragOver}
+ onDragLeave={() => setDropPosition(null)}
+ onDrop={handleDrop}
style={{ paddingLeft: `${8 + depth * 14}px` }}
>
<button
@@ -803,6 +940,7 @@ const NotebookTreeItem = ({
onCreateNotebook={onCreateNotebook}
onRenameNotebook={onRenameNotebook}
onDeleteNotebook={onDeleteNotebook}
+ onMoveNotebook={onMoveNotebook}
/>
))}
</div>
@@ -813,6 +951,7 @@ const NotebookTreeItem = ({
const MemoListPane = ({
notebook,
+ notebooks,
view,
memos,
selectedMemoId,
@@ -821,6 +960,7 @@ const MemoListPane = ({
isLoading,
isCreating,
isMerging,
+ isMoving,
multiSelectKeyDown,
onBackToNotebooks,
onSearch,
@@ -828,8 +968,10 @@ const MemoListPane = ({
onOpenMemo,
onToggleMemo,
onMerge,
+ onMoveSelectedMemos,
}: {
notebook: Notebook | null;
+ notebooks: Notebook[];
view: MemoView;
memos: MemoSummary[];
selectedMemoId: string | null;
@@ -838,6 +980,7 @@ const MemoListPane = ({
isLoading: boolean;
isCreating: boolean;
isMerging: boolean;
+ isMoving: boolean;
multiSelectKeyDown: boolean;
onBackToNotebooks: () => void;
onSearch: (value: string) => void;
@@ -845,7 +988,17 @@ const MemoListPane = ({
onOpenMemo: (memoId: string) => void;
onToggleMemo: (memoId: string) => void;
onMerge: () => void;
-}) => (
+ onMoveSelectedMemos: (notebookId: string) => void;
+}) => {
+ const [moveTargetNotebookId, setMoveTargetNotebookId] = useState(notebook?.id ?? notebooks[0]?.id ?? "");
+
+ useEffect(() => {
+ if (notebook?.id) {
+ setMoveTargetNotebookId(notebook.id);
+ }
+ }, [notebook?.id]);
+
+ return (
<div className="relative flex h-full min-h-0 flex-col">
<header className="border-b border-emerald-100 bg-white px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))] lg:py-3">
<div className="mb-3 flex items-center justify-between gap-3">
@@ -886,20 +1039,44 @@ const MemoListPane = ({
<div className="relative min-h-0 flex-1 overflow-y-auto p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]">
{selectedMemoIds.size > 0 ? (
- <div className="sticky top-0 z-10 mb-3 flex items-center justify-between rounded-md border border-emerald-100 bg-white px-3 py-2 shadow-panel">
+ <div className="sticky top-0 z-10 mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-emerald-100 bg-white px-3 py-2 shadow-panel">
<div className="flex items-center gap-2 text-sm font-medium">
<CheckSquare className="h-4 w-4 text-emerald-700" />
{selectedMemoIds.size} selected
</div>
- <Button
- size="sm"
- variant="solid"
- onClick={onMerge}
- disabled={selectedMemoIds.size < 2 || isMerging || view === "trash"}
- >
- <Merge className="h-4 w-4" />
- 合并
- </Button>
+ <div className="flex min-w-0 flex-wrap items-center gap-2">
+ <select
+ className="h-8 max-w-40 rounded-md border border-emerald-100 bg-emerald-50/70 px-2 text-xs text-emerald-900 outline-none disabled:opacity-50"
+ value={moveTargetNotebookId}
+ disabled={view === "trash" || notebooks.length === 0 || isMoving}
+ onChange={(event) => setMoveTargetNotebookId(event.target.value)}
+ title="移动到笔记本"
+ >
+ {notebooks.map((item) => (
+ <option key={item.id} value={item.id}>
+ {item.name}
+ </option>
+ ))}
+ </select>
+ <Button
+ size="sm"
+ variant="soft"
+ onClick={() => onMoveSelectedMemos(moveTargetNotebookId)}
+ disabled={!moveTargetNotebookId || isMoving || view === "trash"}
+ >
+ <Folder className="h-4 w-4" />
+ 移动
+ </Button>
+ <Button
+ size="sm"
+ variant="solid"
+ onClick={onMerge}
+ disabled={selectedMemoIds.size < 2 || isMerging || view === "trash"}
+ >
+ <Merge className="h-4 w-4" />
+ 合并
+ </Button>
+ </div>
</div>
) : null}
@@ -938,7 +1115,8 @@ const MemoListPane = ({
</button>
) : null}
</div>
-);
+ );
+};
const MemoCard = ({
memo,
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index c4af6638..adc201c6 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -178,6 +178,12 @@ export const api = {
body: JSON.stringify(payload),
}),
+ moveMemos: (payload: { memoIds: string[]; notebookId: string }) =>
+ request<{ ok: true; moved: number }>("/api/v1/memos/batch/move", {
+ method: "POST",
+ body: JSON.stringify(payload),
+ }),
+
getMemo: (memoId: string, options?: { includeDeleted?: boolean }) => {
const search = new URLSearchParams();
diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts
index d6cf2ac4..b4a3c3e5 100644
--- a/packages/shared/src/schemas.ts
+++ b/packages/shared/src/schemas.ts
@@ -27,6 +27,11 @@ export const MemoUpdateSchema = z.object({
tags: z.array(z.string()).optional(),
});
+export const MoveMemosSchema = z.object({
+ memoIds: z.array(z.string().trim().min(1)).min(1).max(100),
+ notebookId: z.string().trim().min(1),
+});
+
export const MergeMemosSchema = z.object({
memoIds: z.array(z.string().trim().min(1)).min(2).max(50),
notebookId: z.string().trim().min(1).optional(),
@@ -52,6 +57,7 @@ export type NotebookCreateInput = z.infer<typeof NotebookCreateSchema>;
export type NotebookUpdateInput = z.infer<typeof NotebookUpdateSchema>;
export type MemoCreateInput = z.infer<typeof MemoCreateSchema>;
export type MemoUpdateInput = z.infer<typeof MemoUpdateSchema>;
+export type MoveMemosInput = z.infer<typeof MoveMemosSchema>;
export type MergeMemosInput = z.infer<typeof MergeMemosSchema>;
export type LoginInput = z.infer<typeof LoginSchema>;
export type ApiTokenCreateInput = z.infer<typeof ApiTokenCreateSchema>;
diff --git a/scripts/edgeever.mjs b/scripts/edgeever.mjs
index a9d66b65..50f49c0f 100644
--- a/scripts/edgeever.mjs
+++ b/scripts/edgeever.mjs
@@ -1,20 +1,35 @@
#!/usr/bin/env bun
-import { readFile } from "node:fs/promises";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { basename, dirname, join } from "node:path";
+import { homedir } from "node:os";
-const baseUrl = (process.env.EDGEEVER_URL || "http://127.0.0.1:8787").replace(/\/+$/, "");
-const token = process.env.EDGEEVER_TOKEN;
-const [, , command, ...argv] = process.argv;
+const CONFIG_PATH = process.env.EDGEEVER_CONFIG || join(homedir(), ".edgeever", "config.json");
+const DEFAULT_URL = "http://127.0.0.1:8787";
+const rawArgs = process.argv.slice(2);
+const globalOptions = parseOptions(rawArgs);
+const commandArgs = stripGlobalOptions(rawArgs, new Set(["profile"]));
+const [command, ...argv] = commandArgs;
const usage = `EdgeEver CLI
Usage:
- EDGEEVER_TOKEN=... bun run cli -- notebooks
- EDGEEVER_TOKEN=... bun run cli -- tags
- EDGEEVER_TOKEN=... bun run cli -- search <query>
- EDGEEVER_TOKEN=... bun run cli -- get <memoId>
- EDGEEVER_TOKEN=... bun run cli -- create --notebook <id> [--title <title>] [--body <markdown> | --body-file <path>] [--tags a,b]
- EDGEEVER_TOKEN=... bun run cli -- update <memoId> [--title <title>] [--body <markdown> | --body-file <path>] [--tags a,b] [--notebook <id>]
+ bun run cli -- profile set <name> --url <url> --token <token>
+ bun run cli -- profile list
+ bun run cli -- --profile <name> notebooks
+ bun run cli -- --profile <name> tags
+ bun run cli -- --profile <name> search <query>
+ bun run cli -- --profile <name> get <memoId>
+ bun run cli -- --profile <name> create --notebook <id> [--title <title>] [--body <markdown> | --body-file <path>] [--tags a,b]
+ bun run cli -- --profile <name> update <memoId> [--title <title>] [--body <markdown> | --body-file <path>] [--tags a,b] [--notebook <id>]
+ bun run cli -- --profile <name> move --notebook <id> <memoId...>
+ bun run cli -- --profile <name> merge [--notebook <id>] [--title <title>] <memoId...>
+ bun run cli -- --profile <name> upload --memo <id> --file <path> [--type <mime>]
+ bun run cli -- --profile <name> export <memoId> [--format markdown|json] [--out <path>]
+
+Env fallback:
+ EDGEEVER_URL=http://127.0.0.1:8787
+ EDGEEVER_TOKEN=...
`;
if (!command || command === "help" || command === "--help" || command === "-h") {
@@ -22,17 +37,18 @@ if (!command || command === "help" || command === "--help" || command === "-h")
process.exit(0);
}
-if (!token) {
- console.error("EDGEEVER_TOKEN is required.");
- process.exit(1);
-}
-
const main = async () => {
+ if (command === "profile") {
+ return handleProfileCommand(argv);
+ }
+
+ const client = await createClient(globalOptions.profile);
+
switch (command) {
case "notebooks":
- return printJson(await request("/api/v1/notebooks"));
+ return printJson(await client.request("/api/v1/notebooks"));
case "tags":
- return printJson(await request("/api/v1/tags"));
+ return printJson(await client.request("/api/v1/tags"));
case "search": {
const query = argv.join(" ").trim();
const params = new URLSearchParams();
@@ -41,19 +57,19 @@ const main = async () => {
params.set("q", query);
}
- return printJson(await request(`/api/v1/memos?${params.toString()}`));
+ return printJson(await client.request(`/api/v1/memos?${params.toString()}`));
}
case "get": {
- const memoId = argv[0];
- requireValue(memoId, "memoId");
- return printJson(await request(`/api/v1/memos/${encodeURIComponent(memoId)}`));
+ const memoId = requireValue(argv[0], "memoId");
+ return printJson(await client.request(`/api/v1/memos/${encodeURIComponent(memoId)}`));
}
case "create": {
const options = parseOptions(argv);
const notebookId = requireValue(options.notebook, "--notebook");
const body = await readBodyOption(options);
+
return printJson(
- await request("/api/v1/memos", {
+ await client.request("/api/v1/memos", {
method: "POST",
body: {
notebookId,
@@ -65,8 +81,7 @@ const main = async () => {
);
}
case "update": {
- const memoId = argv[0];
- requireValue(memoId, "memoId");
+ const memoId = requireValue(argv[0], "memoId");
const options = parseOptions(argv.slice(1));
const body = options.body || options["body-file"] ? await readBodyOption(options) : undefined;
const payload = removeUndefined({
@@ -77,12 +92,62 @@ const main = async () => {
});
return printJson(
- await request(`/api/v1/memos/${encodeURIComponent(memoId)}`, {
+ await client.request(`/api/v1/memos/${encodeURIComponent(memoId)}`, {
method: "PATCH",
body: payload,
})
);
}
+ case "move": {
+ const options = parseOptions(argv);
+ const memoIds = positionalArgs(argv);
+
+ return printJson(
+ await client.request("/api/v1/memos/batch/move", {
+ method: "POST",
+ body: {
+ notebookId: requireValue(options.notebook, "--notebook"),
+ memoIds,
+ },
+ })
+ );
+ }
+ case "merge": {
+ const options = parseOptions(argv);
+ const memoIds = positionalArgs(argv);
+
+ return printJson(
+ await client.request("/api/v1/memos/merge", {
+ method: "POST",
+ body: removeUndefined({
+ notebookId: options.notebook,
+ title: options.title,
+ memoIds,
+ }),
+ })
+ );
+ }
+ case "upload": {
+ const options = parseOptions(argv);
+ const memoId = requireValue(options.memo, "--memo");
+ const filePath = requireValue(options.file, "--file");
+ return printJson(await client.uploadMemoResource(memoId, filePath, options.type));
+ }
+ case "export": {
+ const memoId = requireValue(argv[0], "memoId");
+ const options = parseOptions(argv.slice(1));
+ const format = options.format === "json" ? "json" : "markdown";
+ const data = await client.request(`/api/v1/memos/${encodeURIComponent(memoId)}`);
+ const output = format === "json" ? `${JSON.stringify(data.memo, null, 2)}\n` : data.memo.contentMarkdown;
+
+ if (options.out) {
+ await writeFile(options.out, output);
+ return;
+ }
+
+ process.stdout.write(output);
+ return;
+ }
default:
console.error(`Unknown command: ${command}\n`);
console.error(usage);
@@ -90,7 +155,23 @@ const main = async () => {
}
};
-const request = async (path, init = {}) => {
+const createClient = async (profileName) => {
+ const config = await readConfig();
+ const profile = profileName ? config.profiles?.[profileName] : undefined;
+ const baseUrl = (process.env.EDGEEVER_URL || profile?.url || DEFAULT_URL).replace(/\/+$/, "");
+ const token = process.env.EDGEEVER_TOKEN || profile?.token;
+
+ if (!token) {
+ throw new Error("EDGEEVER_TOKEN is required, or configure a profile with `edgeever profile set`.");
+ }
+
+ return {
+ request: (path, init = {}) => request(baseUrl, token, path, init),
+ uploadMemoResource: (memoId, filePath, mimeType) => uploadMemoResource(baseUrl, token, memoId, filePath, mimeType),
+ };
+};
+
+const request = async (baseUrl, token, path, init = {}) => {
const response = await fetch(`${baseUrl}${path}`, {
method: init.method || "GET",
headers: {
@@ -99,7 +180,28 @@ const request = async (path, init = {}) => {
},
body: init.body === undefined ? undefined : JSON.stringify(init.body),
});
+ const body = await response.json().catch(() => null);
+
+ if (!response.ok) {
+ const message = body?.error?.message || response.statusText;
+ throw new Error(`${response.status} ${message}`);
+ }
+
+ return body;
+};
+
+const uploadMemoResource = async (baseUrl, token, memoId, filePath, mimeType) => {
+ const bytes = await readFile(filePath);
+ const form = new FormData();
+ form.append("file", new File([bytes], basename(filePath), { type: mimeType || inferMimeType(filePath) }));
+ const response = await fetch(`${baseUrl}/api/v1/memos/${encodeURIComponent(memoId)}/resources`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ body: form,
+ });
const body = await response.json().catch(() => null);
if (!response.ok) {
@@ -110,7 +212,51 @@ const request = async (path, init = {}) => {
return body;
};
-const parseOptions = (args) => {
+const handleProfileCommand = async (args) => {
+ const [subcommand, name, ...rest] = args;
+
+ if (subcommand === "list") {
+ const config = await readConfig();
+ return printJson({
+ profiles: Object.entries(config.profiles || {}).map(([profileName, profile]) => ({
+ name: profileName,
+ url: profile.url,
+ hasToken: Boolean(profile.token),
+ })),
+ });
+ }
+
+ if (subcommand === "set") {
+ const profileName = requireValue(name, "profile name");
+ const options = parseOptions(rest);
+ const config = await readConfig();
+ config.profiles = config.profiles || {};
+ config.profiles[profileName] = {
+ url: requireValue(options.url, "--url").replace(/\/+$/, ""),
+ token: requireValue(options.token, "--token"),
+ };
+ await writeConfig(config);
+ return printJson({ ok: true, profile: profileName, path: CONFIG_PATH });
+ }
+
+ throw new Error("Unknown profile command.");
+};
+
+const readConfig = async () => {
+ try {
+ const value = JSON.parse(await readFile(CONFIG_PATH, "utf8"));
+ return value && typeof value === "object" ? value : {};
+ } catch {
+ return {};
+ }
+};
+
+const writeConfig = async (config) => {
+ await mkdir(dirname(CONFIG_PATH), { recursive: true, mode: 0o700 });
+ await writeFile(CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
+};
+
+function parseOptions(args) {
const options = {};
for (let index = 0; index < args.length; index += 1) {
@@ -133,7 +279,47 @@ const parseOptions = (args) => {
}
return options;
-};
+}
+
+function positionalArgs(args) {
+ const values = [];
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (!arg.startsWith("--")) {
+ values.push(arg);
+ continue;
+ }
+
+ const next = args[index + 1];
+
+ if (next && !next.startsWith("--")) {
+ index += 1;
+ }
+ }
+
+ return values;
+}
+
+function stripGlobalOptions(args, globalKeys) {
+ const result = [];
+
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (!arg.startsWith("--") || !globalKeys.has(arg.slice(2))) {
+ result.push(arg);
+ continue;
+ }
+
+ if (args[index + 1] && !args[index + 1].startsWith("--")) {
+ index += 1;
+ }
+ }
+
+ return result;
+}
const readBodyOption = async (options) => {
if (options["body-file"]) {
@@ -151,6 +337,32 @@ const parseTags = (value) =>
.filter(Boolean)
: [];
+const inferMimeType = (filePath) => {
+ const normalized = filePath.toLowerCase();
+
+ if (normalized.endsWith(".png")) {
+ return "image/png";
+ }
+
+ if (normalized.endsWith(".jpg") || normalized.endsWith(".jpeg")) {
+ return "image/jpeg";
+ }
+
+ if (normalized.endsWith(".gif")) {
+ return "image/gif";
+ }
+
+ if (normalized.endsWith(".webp")) {
+ return "image/webp";
+ }
+
+ if (normalized.endsWith(".avif")) {
+ return "image/avif";
+ }
+
+ return "application/octet-stream";
+};
+
const removeUndefined = (value) =>
Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));