micloud-cli 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +661 -0
- package/README.en.md +118 -0
- package/README.md +117 -2
- package/dist/cli.js +59 -0
- package/dist/commands/account.js +76 -0
- package/dist/core/account.js +22 -0
- package/dist/core/auth.js +338 -0
- package/dist/core/config.js +81 -0
- package/dist/core/http.js +172 -0
- package/dist/core/lock.js +90 -0
- package/dist/core/output.js +137 -0
- package/dist/core/template.js +39 -0
- package/dist/core/utils.js +205 -0
- package/dist/note/client.js +298 -0
- package/dist/note/commands/create.js +44 -0
- package/dist/note/commands/delete.js +32 -0
- package/dist/note/commands/export.js +20 -0
- package/dist/note/commands/folder.js +101 -0
- package/dist/note/commands/get.js +35 -0
- package/dist/note/commands/list.js +57 -0
- package/dist/note/commands/move.js +37 -0
- package/dist/note/commands/pin.js +41 -0
- package/dist/note/commands/search.js +45 -0
- package/dist/note/commands/shared.js +37 -0
- package/dist/note/commands/sync.js +217 -0
- package/dist/note/commands/update.js +61 -0
- package/dist/note/commands/upload-image.js +27 -0
- package/dist/note/config.js +166 -0
- package/dist/note/converter.js +664 -0
- package/dist/note/extra-info.js +23 -0
- package/dist/note/images.js +100 -0
- package/dist/note/register.js +172 -0
- package/dist/note/sync-diff.js +143 -0
- package/dist/note/sync.js +748 -0
- package/dist/note/text-diff.js +71 -0
- package/dist/note/types.js +2 -0
- package/dist/recording/client.js +115 -0
- package/dist/recording/commands/config.js +73 -0
- package/dist/recording/commands/delete.js +171 -0
- package/dist/recording/commands/list.js +161 -0
- package/dist/recording/commands/shared.js +47 -0
- package/dist/recording/commands/transfer.js +192 -0
- package/dist/recording/commands/trash.js +140 -0
- package/dist/recording/config.js +104 -0
- package/dist/recording/dates.js +61 -0
- package/dist/recording/download.js +308 -0
- package/dist/recording/progress.js +77 -0
- package/dist/recording/pull.js +433 -0
- package/dist/recording/recording.js +294 -0
- package/dist/recording/register.js +202 -0
- package/dist/recording/template.js +44 -0
- package/dist/recording/types.js +2 -0
- package/package.json +53 -4
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { getClient, resolveContent, contentBaseDir } from "./shared.js";
|
|
2
|
+
import { markdownToXml, extractSnippet } from "../converter.js";
|
|
3
|
+
import { uploadLocalImages, withAttachments } from "../images.js";
|
|
4
|
+
import { buildExtraInfoString } from "../extra-info.js";
|
|
5
|
+
import { success, logInfo, fail } from "../../core/output.js";
|
|
6
|
+
/** 创建笔记 */
|
|
7
|
+
export async function createCommand(opts) {
|
|
8
|
+
try {
|
|
9
|
+
const content = await resolveContent(opts);
|
|
10
|
+
if (content === null || content.trim() === "") {
|
|
11
|
+
throw new Error("笔记内容为空。请通过 --content、--file 或标准输入(管道)提供内容。");
|
|
12
|
+
}
|
|
13
|
+
let colorId = 0;
|
|
14
|
+
if (opts.color !== undefined) {
|
|
15
|
+
colorId = parseInt(opts.color, 10);
|
|
16
|
+
if (Number.isNaN(colorId)) {
|
|
17
|
+
throw new Error(`--color 必须是数字,收到:${opts.color}`);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
const client = await getClient();
|
|
21
|
+
const { imageMap, uploaded } = await uploadLocalImages(client, content, new Map(), [contentBaseDir(opts)]);
|
|
22
|
+
const now = Date.now();
|
|
23
|
+
const xmlContent = markdownToXml(content, imageMap);
|
|
24
|
+
const entry = {
|
|
25
|
+
colorId,
|
|
26
|
+
folderId: opts.folder ?? "0",
|
|
27
|
+
createDate: now,
|
|
28
|
+
modifyDate: now,
|
|
29
|
+
content: xmlContent,
|
|
30
|
+
alertDate: 0,
|
|
31
|
+
setting: withAttachments(undefined, uploaded),
|
|
32
|
+
extraInfo: buildExtraInfoString(opts.title),
|
|
33
|
+
snippet: extractSnippet(xmlContent),
|
|
34
|
+
};
|
|
35
|
+
const created = await client.createNote(entry);
|
|
36
|
+
const id = String(created.id);
|
|
37
|
+
success({ id, title: opts.title ?? "", folderId: entry.folderId }, () => {
|
|
38
|
+
logInfo(`✅ 创建成功:${id}`);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
catch (err) {
|
|
42
|
+
fail(err);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { parseNoteEntry } from "../converter.js";
|
|
3
|
+
import { success, logInfo, fail, assertCanConfirm, confirmDestructive } from "../../core/output.js";
|
|
4
|
+
/** 删除笔记(默认移回收站,--purge 永久删除) */
|
|
5
|
+
export async function deleteCommand(id, opts) {
|
|
6
|
+
try {
|
|
7
|
+
assertCanConfirm(opts.yes);
|
|
8
|
+
const client = await getClient();
|
|
9
|
+
const entry = await client.getNote(id);
|
|
10
|
+
const note = parseNoteEntry(entry);
|
|
11
|
+
if (!entry.tag) {
|
|
12
|
+
throw new Error("笔记缺少 tag 字段,无法删除");
|
|
13
|
+
}
|
|
14
|
+
if (!opts.yes) {
|
|
15
|
+
const action = opts.purge ? "永久删除" : "移到回收站";
|
|
16
|
+
logInfo(`📝 笔记: ${note.subject || "(无标题)"} [${id}]`);
|
|
17
|
+
if (!(await confirmDestructive(`确认要${action}该笔记吗?`, opts.yes))) {
|
|
18
|
+
logInfo("已取消");
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
await client.deleteNote(id, entry.tag, opts.purge ?? false);
|
|
23
|
+
success({ id, purged: opts.purge ?? false }, () => {
|
|
24
|
+
logInfo(opts.purge
|
|
25
|
+
? `✅ 笔记 ${id} 已永久删除`
|
|
26
|
+
: `✅ 笔记 ${id} 已移到回收站(30 天内可在小米云服务网页端恢复)`);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
catch (err) {
|
|
30
|
+
fail(err);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { exportNotes } from "../sync.js";
|
|
3
|
+
import { resolveOutputDir } from "../config.js";
|
|
4
|
+
import { isJsonMode, success, fail, EXIT_PARTIAL_FAILURE } from "../../core/output.js";
|
|
5
|
+
/** 导出笔记到本地 Markdown(单向云→本地,永不修改云端) */
|
|
6
|
+
export async function exportCommand(opts) {
|
|
7
|
+
try {
|
|
8
|
+
const outputDir = await resolveOutputDir(opts.output);
|
|
9
|
+
const client = await getClient();
|
|
10
|
+
const result = await exportNotes(client, outputDir, opts.force ?? false, isJsonMode());
|
|
11
|
+
success(result, () => {
|
|
12
|
+
// 过程已打印汇总
|
|
13
|
+
});
|
|
14
|
+
if (result.errors.length > 0)
|
|
15
|
+
process.exitCode = EXIT_PARTIAL_FAILURE;
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
fail(err);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { success, logInfo, fail, assertCanConfirm, confirmDestructive } from "../../core/output.js";
|
|
3
|
+
/** 列出所有文件夹 */
|
|
4
|
+
export async function foldersCommand() {
|
|
5
|
+
try {
|
|
6
|
+
const client = await getClient();
|
|
7
|
+
const { folders } = await client.getAllNotes(200);
|
|
8
|
+
process.stderr.write("\r");
|
|
9
|
+
const list = Object.values(folders).map((f) => ({
|
|
10
|
+
id: String(f.id),
|
|
11
|
+
subject: f.subject ?? "",
|
|
12
|
+
parentId: String(f.folderId ?? "0"),
|
|
13
|
+
}));
|
|
14
|
+
success(list, () => {
|
|
15
|
+
if (list.length === 0) {
|
|
16
|
+
logInfo("(无文件夹)");
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
for (const f of list) {
|
|
20
|
+
process.stdout.write(`[${f.id}] ${f.subject}\n`);
|
|
21
|
+
}
|
|
22
|
+
logInfo(`\n共 ${list.length} 个文件夹`);
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
catch (err) {
|
|
26
|
+
fail(err);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** 创建文件夹 */
|
|
30
|
+
export async function folderCreateCommand(name, opts) {
|
|
31
|
+
try {
|
|
32
|
+
const client = await getClient();
|
|
33
|
+
const folder = await client.createFolder(name, opts.parent ?? "0");
|
|
34
|
+
success({ id: String(folder.id), subject: name }, () => {
|
|
35
|
+
logInfo(`✅ 文件夹创建成功:[${folder.id}] ${name}`);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
fail(err);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** 重命名文件夹 */
|
|
43
|
+
export async function folderRenameCommand(id, name) {
|
|
44
|
+
try {
|
|
45
|
+
const client = await getClient();
|
|
46
|
+
const { folders } = await client.getAllNotes(200);
|
|
47
|
+
process.stderr.write("\r");
|
|
48
|
+
const folder = folders[id];
|
|
49
|
+
if (!folder)
|
|
50
|
+
throw new Error(`未找到文件夹:${id}`);
|
|
51
|
+
const entry = {
|
|
52
|
+
id: String(folder.id),
|
|
53
|
+
tag: folder.tag,
|
|
54
|
+
status: folder.status,
|
|
55
|
+
createDate: folder.createDate ?? Date.now(),
|
|
56
|
+
modifyDate: Date.now(),
|
|
57
|
+
colorId: folder.colorId ?? 0,
|
|
58
|
+
type: "folder",
|
|
59
|
+
folderId: String(folder.folderId ?? "0"),
|
|
60
|
+
subject: name,
|
|
61
|
+
setting: folder.setting ?? { themeId: 0, stickyTime: 0, version: 0 },
|
|
62
|
+
};
|
|
63
|
+
await client.updateFolder(id, entry);
|
|
64
|
+
success({ id, subject: name }, () => {
|
|
65
|
+
logInfo(`✅ 文件夹 ${id} 已重命名为「${name}」`);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
fail(err);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** 删除文件夹 */
|
|
73
|
+
export async function folderDeleteCommand(id, opts) {
|
|
74
|
+
try {
|
|
75
|
+
assertCanConfirm(opts.yes);
|
|
76
|
+
const client = await getClient();
|
|
77
|
+
const { folders } = await client.getAllNotes(200);
|
|
78
|
+
process.stderr.write("\r");
|
|
79
|
+
const folder = folders[id];
|
|
80
|
+
if (!folder)
|
|
81
|
+
throw new Error(`未找到文件夹:${id}`);
|
|
82
|
+
if (!folder.tag)
|
|
83
|
+
throw new Error("文件夹缺少 tag 字段,无法删除");
|
|
84
|
+
if (!opts.yes) {
|
|
85
|
+
const action = opts.purge ? "永久删除" : "删除";
|
|
86
|
+
logInfo(`📁 文件夹: ${folder.subject ?? ""} [${id}]`);
|
|
87
|
+
const ok = await confirmDestructive(`确认要${action}该文件夹吗?(文件夹内笔记也会一并处理)`, opts.yes);
|
|
88
|
+
if (!ok) {
|
|
89
|
+
logInfo("已取消");
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
await client.deleteFolder(id, folder.tag, opts.purge ?? false);
|
|
94
|
+
success({ id, purged: opts.purge ?? false }, () => {
|
|
95
|
+
logInfo(opts.purge ? `✅ 文件夹 ${id} 已永久删除` : `✅ 文件夹 ${id} 已删除`);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
fail(err);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { parseNoteEntry, xmlToMarkdown, deriveTitle } from "../converter.js";
|
|
3
|
+
import { isJsonMode, output, success, fail } from "../../core/output.js";
|
|
4
|
+
/** 获取单条笔记内容 */
|
|
5
|
+
export async function getCommand(id, opts) {
|
|
6
|
+
try {
|
|
7
|
+
const client = await getClient();
|
|
8
|
+
const entry = await client.getNote(id);
|
|
9
|
+
if (opts.raw) {
|
|
10
|
+
// 输出原始 XML 内容
|
|
11
|
+
output(entry.content ?? "", "content");
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const parsed = parseNoteEntry(entry);
|
|
15
|
+
const markdown = xmlToMarkdown(parsed.content, parsed.files);
|
|
16
|
+
const title = deriveTitle(entry);
|
|
17
|
+
if (isJsonMode()) {
|
|
18
|
+
success({
|
|
19
|
+
id: parsed.id,
|
|
20
|
+
title,
|
|
21
|
+
folderId: parsed.folderId,
|
|
22
|
+
createDate: parsed.createDate,
|
|
23
|
+
modifyDate: parsed.modifyDate,
|
|
24
|
+
content: markdown,
|
|
25
|
+
files: parsed.files.map((f) => ({ fileId: f.fileId, name: f.name })),
|
|
26
|
+
}, () => { });
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
output(markdown, "content");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
fail(err);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { getClient, parseLimit } from "./shared.js";
|
|
2
|
+
import { deriveTitle, xmlToMarkdown } from "../converter.js";
|
|
3
|
+
import { truncateDisplay } from "../../core/utils.js";
|
|
4
|
+
import { success, logInfo, fail } from "../../core/output.js";
|
|
5
|
+
/** list 输出中单行标题的最大显示宽度(超出截断加省略号) */
|
|
6
|
+
const TITLE_MAX_WIDTH = 60;
|
|
7
|
+
/** 列出笔记 */
|
|
8
|
+
export async function listCommand(opts) {
|
|
9
|
+
try {
|
|
10
|
+
const limit = parseLimit(opts.limit, Infinity);
|
|
11
|
+
const client = await getClient();
|
|
12
|
+
const { entries, folders } = await client.getAllNotes(200, (count) => {
|
|
13
|
+
process.stderr.write(`\r📋 已获取 ${count} 条笔记...`);
|
|
14
|
+
});
|
|
15
|
+
process.stderr.write("\r");
|
|
16
|
+
let filtered = entries;
|
|
17
|
+
if (opts.folder) {
|
|
18
|
+
filtered = filtered.filter((e) => String(e.folderId ?? "") === opts.folder);
|
|
19
|
+
}
|
|
20
|
+
// 按修改时间倒序
|
|
21
|
+
filtered.sort((a, b) => (b.modifyDate ?? 0) - (a.modifyDate ?? 0));
|
|
22
|
+
const sliced = filtered.slice(0, limit);
|
|
23
|
+
const items = sliced.map((e) => toListItem(e));
|
|
24
|
+
success(items, () => {
|
|
25
|
+
if (items.length === 0) {
|
|
26
|
+
logInfo("(无笔记)");
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
for (const it of items) {
|
|
30
|
+
const time = it.modifyDate
|
|
31
|
+
? new Date(it.modifyDate).toLocaleString("zh-CN")
|
|
32
|
+
: "";
|
|
33
|
+
const folderName = it.folderId && it.folderId !== "0"
|
|
34
|
+
? folders[it.folderId]?.subject ?? it.folderId
|
|
35
|
+
: "";
|
|
36
|
+
const folderTag = folderName ? ` 📁${folderName}` : "";
|
|
37
|
+
// 人类可读输出做显示截断,避免无标题笔记的长正文首行刷屏
|
|
38
|
+
const title = truncateDisplay(it.title, TITLE_MAX_WIDTH);
|
|
39
|
+
process.stdout.write(`[${it.id}] ${title}${folderTag} (${time})\n`);
|
|
40
|
+
}
|
|
41
|
+
logInfo(`\n共 ${items.length} 条`);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
catch (err) {
|
|
45
|
+
fail(err);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function toListItem(e) {
|
|
49
|
+
return {
|
|
50
|
+
id: String(e.id),
|
|
51
|
+
// JSON 输出保留完整标题,截断只发生在人类可读渲染层
|
|
52
|
+
title: deriveTitle(e),
|
|
53
|
+
snippet: xmlToMarkdown(e.snippet ?? "").slice(0, 100),
|
|
54
|
+
modifyDate: e.modifyDate,
|
|
55
|
+
folderId: String(e.folderId ?? ""),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { success, logInfo, fail } from "../../core/output.js";
|
|
3
|
+
/** 将笔记移动到指定文件夹(复用更新接口,改 folderId) */
|
|
4
|
+
export async function moveCommand(id, folderId) {
|
|
5
|
+
try {
|
|
6
|
+
const client = await getClient();
|
|
7
|
+
const current = await client.getNote(id);
|
|
8
|
+
if (String(current.folderId ?? "0") === folderId) {
|
|
9
|
+
success({ id, folderId, moved: false }, () => {
|
|
10
|
+
logInfo("笔记已在目标文件夹中");
|
|
11
|
+
});
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
const entry = {
|
|
15
|
+
id: String(current.id),
|
|
16
|
+
tag: current.tag,
|
|
17
|
+
status: current.status,
|
|
18
|
+
createDate: current.createDate ?? Date.now(),
|
|
19
|
+
modifyDate: Date.now(),
|
|
20
|
+
colorId: current.colorId ?? 0,
|
|
21
|
+
content: current.content ?? "",
|
|
22
|
+
setting: current.setting,
|
|
23
|
+
folderId,
|
|
24
|
+
alertDate: current.alertDate ?? 0,
|
|
25
|
+
extraInfo: typeof current.extraInfo === "string" ? current.extraInfo : undefined,
|
|
26
|
+
subject: current.subject,
|
|
27
|
+
snippet: current.snippet,
|
|
28
|
+
};
|
|
29
|
+
await client.updateNote(id, entry);
|
|
30
|
+
success({ id, folderId, moved: true }, () => {
|
|
31
|
+
logInfo(`✅ 笔记 ${id} 已移动到文件夹 ${folderId}`);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
fail(err);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { success, logInfo, fail } from "../../core/output.js";
|
|
3
|
+
/**
|
|
4
|
+
* 置顶 / 取消置顶笔记。
|
|
5
|
+
*
|
|
6
|
+
* 置顶通过 setting.stickyTime 实现:>0 表示置顶(用当前时间戳),0 表示取消。
|
|
7
|
+
*/
|
|
8
|
+
export async function pinCommand(id, pin) {
|
|
9
|
+
try {
|
|
10
|
+
const client = await getClient();
|
|
11
|
+
const current = await client.getNote(id);
|
|
12
|
+
const stickyTime = pin ? Date.now() : 0;
|
|
13
|
+
const entry = {
|
|
14
|
+
id: String(current.id),
|
|
15
|
+
tag: current.tag,
|
|
16
|
+
status: current.status,
|
|
17
|
+
createDate: current.createDate ?? Date.now(),
|
|
18
|
+
modifyDate: Date.now(),
|
|
19
|
+
colorId: current.colorId ?? 0,
|
|
20
|
+
content: current.content ?? "",
|
|
21
|
+
setting: {
|
|
22
|
+
themeId: current.setting?.themeId ?? 0,
|
|
23
|
+
stickyTime,
|
|
24
|
+
version: current.setting?.version ?? 0,
|
|
25
|
+
data: current.setting?.data,
|
|
26
|
+
},
|
|
27
|
+
folderId: String(current.folderId ?? "0"),
|
|
28
|
+
alertDate: current.alertDate ?? 0,
|
|
29
|
+
extraInfo: typeof current.extraInfo === "string" ? current.extraInfo : undefined,
|
|
30
|
+
subject: current.subject,
|
|
31
|
+
snippet: current.snippet,
|
|
32
|
+
};
|
|
33
|
+
await client.updateNote(id, entry);
|
|
34
|
+
success({ id, pinned: pin }, () => {
|
|
35
|
+
logInfo(pin ? `✅ 笔记 ${id} 已置顶` : `✅ 笔记 ${id} 已取消置顶`);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
fail(err);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { getClient, parseLimit } from "./shared.js";
|
|
2
|
+
import { deriveTitle, xmlToMarkdown } from "../converter.js";
|
|
3
|
+
import { success, logInfo, fail } from "../../core/output.js";
|
|
4
|
+
/** 关键词搜索笔记(匹配标题与摘要,不区分大小写) */
|
|
5
|
+
export async function searchCommand(keyword, opts) {
|
|
6
|
+
try {
|
|
7
|
+
const limit = parseLimit(opts.limit, 20);
|
|
8
|
+
const client = await getClient();
|
|
9
|
+
const { entries } = await client.getAllNotes(200, (count) => {
|
|
10
|
+
process.stderr.write(`\r🔍 已检索 ${count} 条...`);
|
|
11
|
+
});
|
|
12
|
+
process.stderr.write("\r");
|
|
13
|
+
const kw = keyword.toLowerCase();
|
|
14
|
+
const matches = entries.filter((e) => {
|
|
15
|
+
const title = deriveTitle(e).toLowerCase();
|
|
16
|
+
const snippet = xmlToMarkdown(e.snippet ?? "").toLowerCase();
|
|
17
|
+
return title.includes(kw) || snippet.includes(kw);
|
|
18
|
+
});
|
|
19
|
+
matches.sort((a, b) => (b.modifyDate ?? 0) - (a.modifyDate ?? 0));
|
|
20
|
+
const sliced = matches.slice(0, limit);
|
|
21
|
+
const items = sliced.map((e) => ({
|
|
22
|
+
id: String(e.id),
|
|
23
|
+
title: deriveTitle(e),
|
|
24
|
+
snippet: xmlToMarkdown(e.snippet ?? "").slice(0, 100),
|
|
25
|
+
modifyDate: e.modifyDate,
|
|
26
|
+
folderId: String(e.folderId ?? ""),
|
|
27
|
+
}));
|
|
28
|
+
success(items, () => {
|
|
29
|
+
if (items.length === 0) {
|
|
30
|
+
logInfo("未找到匹配的笔记");
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
items.forEach((it, i) => {
|
|
34
|
+
const time = it.modifyDate
|
|
35
|
+
? new Date(it.modifyDate).toLocaleString("zh-CN")
|
|
36
|
+
: "";
|
|
37
|
+
process.stdout.write(`${i + 1}. [${it.id}] ${it.title} (${time})\n`);
|
|
38
|
+
});
|
|
39
|
+
logInfo(`\n共 ${items.length} 条匹配`);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
fail(err);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { resolveAuth, refreshAuth } from "../../core/auth.js";
|
|
4
|
+
import { readStdin } from "../../core/output.js";
|
|
5
|
+
import { MiNoteClient } from "../client.js";
|
|
6
|
+
/** 已登录的笔记客户端;请求遇 401 时自动静默续期并重试 */
|
|
7
|
+
export async function getClient() {
|
|
8
|
+
return new MiNoteClient(await resolveAuth(), refreshAuth);
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* 解析笔记内容来源:优先级 --content > --file > stdin。
|
|
12
|
+
* 返回内容字符串;若都没有则返回 null。
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveContent(opts) {
|
|
15
|
+
if (opts.content !== undefined)
|
|
16
|
+
return opts.content;
|
|
17
|
+
if (opts.file) {
|
|
18
|
+
return await readFile(opts.file, "utf-8");
|
|
19
|
+
}
|
|
20
|
+
return await readStdin();
|
|
21
|
+
}
|
|
22
|
+
/** 内容里本地图片相对路径的基准目录:--file 时为文件所在目录,否则为当前目录 */
|
|
23
|
+
export function contentBaseDir(opts) {
|
|
24
|
+
return opts.content === undefined && opts.file
|
|
25
|
+
? dirname(resolve(opts.file))
|
|
26
|
+
: process.cwd();
|
|
27
|
+
}
|
|
28
|
+
/** 解析 --limit:必须是正整数;未提供时返回 fallback */
|
|
29
|
+
export function parseLimit(raw, fallback) {
|
|
30
|
+
if (raw === undefined)
|
|
31
|
+
return fallback;
|
|
32
|
+
const n = Number(raw);
|
|
33
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
34
|
+
throw new Error(`--limit 必须是正整数,收到:${raw}`);
|
|
35
|
+
}
|
|
36
|
+
return n;
|
|
37
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { getClient } from "./shared.js";
|
|
2
|
+
import { buildSyncPlan, executeSyncPlan, emptyApplied, } from "../sync.js";
|
|
3
|
+
import { resolveSyncMode, resolveOutputDir, setSyncMode, loadUserConfig, loadState, saveState, getUserConfigPath, getStatePath, getEffectiveUserConfigPath, hasLegacyOnlyState, ALL_MODES, } from "../config.js";
|
|
4
|
+
import { isJsonMode, success, logInfo, fail, prompt, EXIT_PARTIAL_FAILURE, } from "../../core/output.js";
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
import { actionForSide } from "../sync-diff.js";
|
|
7
|
+
import { diffLines, formatDiff } from "../text-diff.js";
|
|
8
|
+
const MODE_DESC = {
|
|
9
|
+
"cloud-first": "云端优先:仅下行,冲突以云端为准",
|
|
10
|
+
"local-first": "本地优先:仅上行,冲突以本地为准",
|
|
11
|
+
"two-way": "双向自动:单边改自动同步,真冲突才停下询问",
|
|
12
|
+
manual: "交互(默认):任何不一致都列出并逐条询问",
|
|
13
|
+
};
|
|
14
|
+
/** 场景的人类可读说明 */
|
|
15
|
+
const SCENARIO_DESC = {
|
|
16
|
+
"both-changed": "云端与本地都修改了",
|
|
17
|
+
"remote-deleted-local-changed": "云端已删除,但本地有修改",
|
|
18
|
+
"local-deleted-remote-changed": "本地已删除,但云端有修改",
|
|
19
|
+
"local-changed": "本地有修改",
|
|
20
|
+
"local-new": "本地新增",
|
|
21
|
+
"remote-deleted-local-clean": "云端已删除",
|
|
22
|
+
"local-deleted-remote-clean": "本地已删除",
|
|
23
|
+
};
|
|
24
|
+
/** 动作的人类可读说明(冲突询问时展示每个选项的实际后果) */
|
|
25
|
+
const ACTION_DESC = {
|
|
26
|
+
skip: "不做处理",
|
|
27
|
+
"update-local": "用云端内容覆盖本地文件",
|
|
28
|
+
"update-remote": "用本地内容覆盖云端笔记",
|
|
29
|
+
"create-local": "从云端重新生成本地文件",
|
|
30
|
+
"create-remote": "在云端新建笔记",
|
|
31
|
+
"delete-local": "删除本地文件",
|
|
32
|
+
"delete-remote": "把云端笔记移到回收站",
|
|
33
|
+
"drop-state": "清理同步记录",
|
|
34
|
+
conflict: "待定",
|
|
35
|
+
};
|
|
36
|
+
/** sync 主命令 */
|
|
37
|
+
export async function syncCommand(opts) {
|
|
38
|
+
try {
|
|
39
|
+
if (opts.mode && !ALL_MODES.includes(opts.mode)) {
|
|
40
|
+
throw new Error(`未知模式:${opts.mode}。可选:${ALL_MODES.join(" / ")}`);
|
|
41
|
+
}
|
|
42
|
+
const outputDir = await resolveOutputDir(opts.output);
|
|
43
|
+
const mode = await resolveSyncMode(opts.mode);
|
|
44
|
+
const client = await getClient();
|
|
45
|
+
logInfo(`🔁 同步模式:${mode}(${MODE_DESC[mode]})`);
|
|
46
|
+
const { plan, state, folders, stateChanged } = await buildSyncPlan(client, outputDir, mode, isJsonMode());
|
|
47
|
+
if (plan.length === 0) {
|
|
48
|
+
// 首次同步认领了已有本地文件、或旧版状态文件需改存新名字时:虽无动作,但状态需要落盘
|
|
49
|
+
if ((stateChanged || (await hasLegacyOnlyState(outputDir))) && !opts.dryRun) {
|
|
50
|
+
state.lastSync = Date.now();
|
|
51
|
+
await saveState(outputDir, state);
|
|
52
|
+
}
|
|
53
|
+
success(emptyResult(outputDir, mode, !!opts.dryRun), () => {
|
|
54
|
+
logInfo("✅ 已是最新,无需同步");
|
|
55
|
+
});
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
// dry-run:只报告计划
|
|
59
|
+
if (opts.dryRun) {
|
|
60
|
+
const result = await executeSyncPlan(client, outputDir, mode, plan, state, folders, {
|
|
61
|
+
dryRun: true,
|
|
62
|
+
quiet: isJsonMode(),
|
|
63
|
+
});
|
|
64
|
+
success({ ...result, plan: planSummary(plan) }, () => {
|
|
65
|
+
logInfo("📋 同步计划(dry-run,未执行):");
|
|
66
|
+
for (const it of plan) {
|
|
67
|
+
logInfo(` [${it.id}] ${it.subject} — ${describe(it)} → ${it.action}`);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
// 冲突解决器:交互模式询问;非交互/--json 不提供 resolver(跳过并报告)
|
|
73
|
+
const interactive = !isJsonMode() && process.stdout.isTTY && !opts.yes;
|
|
74
|
+
const resolver = interactive ? makeInteractiveResolver() : undefined;
|
|
75
|
+
const result = await executeSyncPlan(client, outputDir, mode, plan, state, folders, {
|
|
76
|
+
quiet: isJsonMode(),
|
|
77
|
+
resolveConflict: resolver,
|
|
78
|
+
});
|
|
79
|
+
success({ ...result, plan: planSummary(plan) }, () => {
|
|
80
|
+
logInfo("\n📊 同步完成:");
|
|
81
|
+
for (const [action, n] of Object.entries(result.applied)) {
|
|
82
|
+
if (n > 0)
|
|
83
|
+
logInfo(` ${action}: ${n}`);
|
|
84
|
+
}
|
|
85
|
+
if (result.conflicts.length > 0) {
|
|
86
|
+
logInfo(`\n⚠️ ${result.conflicts.length} 条冲突未处理(非交互环境已跳过,未改动数据):`);
|
|
87
|
+
for (const c of result.conflicts) {
|
|
88
|
+
logInfo(` [${c.id}] ${c.subject} — ${describe(c)}`);
|
|
89
|
+
}
|
|
90
|
+
logInfo(" 可在交互式终端重跑 sync 逐条处理,或指定 --mode 决定优先方。");
|
|
91
|
+
}
|
|
92
|
+
if (result.errors.length > 0) {
|
|
93
|
+
logInfo(`\n❌ ${result.errors.length} 条处理失败:`);
|
|
94
|
+
for (const e of result.errors) {
|
|
95
|
+
logInfo(` [${e.id}] ${e.subject} — ${e.action}: ${e.error}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
if (result.errors.length > 0)
|
|
100
|
+
process.exitCode = EXIT_PARTIAL_FAILURE;
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
fail(err);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** sync init:交互引导设置项目默认模式 */
|
|
107
|
+
export async function syncInitCommand() {
|
|
108
|
+
try {
|
|
109
|
+
if (isJsonMode() || !process.stdout.isTTY) {
|
|
110
|
+
throw new Error("init 需在交互式终端运行");
|
|
111
|
+
}
|
|
112
|
+
logInfo("🧭 笔记同步初始化\n");
|
|
113
|
+
logInfo("可选同步模式:");
|
|
114
|
+
ALL_MODES.forEach((m, i) => {
|
|
115
|
+
logInfo(` ${i + 1}) ${m} — ${MODE_DESC[m]}`);
|
|
116
|
+
});
|
|
117
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
118
|
+
const ask = (q) => new Promise((res) => rl.question(q, res));
|
|
119
|
+
const idxStr = await ask(`\n选择默认模式 [1-${ALL_MODES.length},默认 ${ALL_MODES.length} manual]: `);
|
|
120
|
+
const idx = parseInt(idxStr.trim(), 10);
|
|
121
|
+
const mode = idx >= 1 && idx <= ALL_MODES.length ? ALL_MODES[idx - 1] : "manual";
|
|
122
|
+
await setSyncMode(mode);
|
|
123
|
+
rl.close();
|
|
124
|
+
success({ mode, configPath: getUserConfigPath() }, () => {
|
|
125
|
+
logInfo(`\n✅ 已将项目默认同步模式设为:${mode}`);
|
|
126
|
+
logInfo(` 配置文件:${getUserConfigPath()}`);
|
|
127
|
+
logInfo(` 提示:可在该文件的 note 节中加 "output" 字段设置默认同步目录。`);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
catch (err) {
|
|
131
|
+
fail(err);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** sync status:查看用户配置 + 当前 output 的同步状态 */
|
|
135
|
+
export async function syncStatusCommand(opts) {
|
|
136
|
+
try {
|
|
137
|
+
const config = await loadUserConfig();
|
|
138
|
+
const configFile = await getEffectiveUserConfigPath();
|
|
139
|
+
const outputDir = await resolveOutputDir(opts.output);
|
|
140
|
+
const state = await loadState(outputDir);
|
|
141
|
+
success({ configFile, config, outputDir, state }, () => {
|
|
142
|
+
logInfo(`配置文件:${configFile}`);
|
|
143
|
+
logInfo(`同步模式:${config.syncMode ?? "manual(默认)"}`);
|
|
144
|
+
if (config.output)
|
|
145
|
+
logInfo(`默认目录:${config.output}`);
|
|
146
|
+
if (config.fileNameTemplate)
|
|
147
|
+
logInfo(`文件名模板:${config.fileNameTemplate}`);
|
|
148
|
+
logInfo(`\n输出目录:${outputDir}`);
|
|
149
|
+
logInfo(`状态文件:${getStatePath(outputDir)}`);
|
|
150
|
+
const last = state.lastSync
|
|
151
|
+
? new Date(state.lastSync).toLocaleString("zh-CN")
|
|
152
|
+
: "从未";
|
|
153
|
+
logInfo(`笔记记录:${Object.keys(state.notes).length} 上次同步:${last}`);
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
fail(err);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// ---- 辅助 ----
|
|
161
|
+
function describe(it) {
|
|
162
|
+
return SCENARIO_DESC[it.scenario] ?? it.scenario;
|
|
163
|
+
}
|
|
164
|
+
/** 无需同步时的结果:结构与有变更时一致,调用方无需区分两种形态 */
|
|
165
|
+
function emptyResult(outputDir, mode, dryRun) {
|
|
166
|
+
return {
|
|
167
|
+
total: 0,
|
|
168
|
+
applied: emptyApplied(),
|
|
169
|
+
conflicts: [],
|
|
170
|
+
errors: [],
|
|
171
|
+
outputDir,
|
|
172
|
+
mode,
|
|
173
|
+
dryRun,
|
|
174
|
+
plan: [],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function planSummary(plan) {
|
|
178
|
+
return plan.map((it) => ({
|
|
179
|
+
id: it.id,
|
|
180
|
+
subject: it.subject,
|
|
181
|
+
scenario: it.scenario,
|
|
182
|
+
action: it.action,
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
/** 构造交互式冲突解决器 */
|
|
186
|
+
function makeInteractiveResolver() {
|
|
187
|
+
return async (item) => {
|
|
188
|
+
const localAction = actionForSide(item.scenario, "local");
|
|
189
|
+
const remoteAction = actionForSide(item.scenario, "remote");
|
|
190
|
+
logInfo(`\n⚠️ 冲突 [${item.id}] ${item.subject}:${describe(item)}`);
|
|
191
|
+
logInfo(" 选择处理方式:");
|
|
192
|
+
logInfo(` (l) 以本地为准:${ACTION_DESC[localAction]}`);
|
|
193
|
+
logInfo(` (r) 以云端为准:${ACTION_DESC[remoteAction]}`);
|
|
194
|
+
logInfo(" (d) 查看差异");
|
|
195
|
+
logInfo(" (s) 跳过");
|
|
196
|
+
while (true) {
|
|
197
|
+
const ans = (await prompt(" 你的选择 [l/r/d/s,默认 s]: ")).toLowerCase();
|
|
198
|
+
if (ans === "d") {
|
|
199
|
+
logInfo(renderConflictDiff(item));
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (ans === "l")
|
|
203
|
+
return localAction;
|
|
204
|
+
if (ans === "r")
|
|
205
|
+
return remoteAction;
|
|
206
|
+
return "skip";
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function renderConflictDiff(item) {
|
|
211
|
+
const header = " --- 云端\n +++ 本地";
|
|
212
|
+
if (item.remoteMarkdown === undefined)
|
|
213
|
+
return `${header}\n (云端不存在,本地内容如下)\n${item.localMarkdown ?? ""}`;
|
|
214
|
+
if (item.localMarkdown === undefined)
|
|
215
|
+
return `${header}\n (本地不存在,云端内容如下)\n${item.remoteMarkdown}`;
|
|
216
|
+
return `${header}\n${formatDiff(diffLines(item.remoteMarkdown, item.localMarkdown))}`;
|
|
217
|
+
}
|