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.
Files changed (53) hide show
  1. package/LICENSE +661 -0
  2. package/README.en.md +118 -0
  3. package/README.md +117 -2
  4. package/dist/cli.js +59 -0
  5. package/dist/commands/account.js +76 -0
  6. package/dist/core/account.js +22 -0
  7. package/dist/core/auth.js +338 -0
  8. package/dist/core/config.js +81 -0
  9. package/dist/core/http.js +172 -0
  10. package/dist/core/lock.js +90 -0
  11. package/dist/core/output.js +137 -0
  12. package/dist/core/template.js +39 -0
  13. package/dist/core/utils.js +205 -0
  14. package/dist/note/client.js +298 -0
  15. package/dist/note/commands/create.js +44 -0
  16. package/dist/note/commands/delete.js +32 -0
  17. package/dist/note/commands/export.js +20 -0
  18. package/dist/note/commands/folder.js +101 -0
  19. package/dist/note/commands/get.js +35 -0
  20. package/dist/note/commands/list.js +57 -0
  21. package/dist/note/commands/move.js +37 -0
  22. package/dist/note/commands/pin.js +41 -0
  23. package/dist/note/commands/search.js +45 -0
  24. package/dist/note/commands/shared.js +37 -0
  25. package/dist/note/commands/sync.js +217 -0
  26. package/dist/note/commands/update.js +61 -0
  27. package/dist/note/commands/upload-image.js +27 -0
  28. package/dist/note/config.js +166 -0
  29. package/dist/note/converter.js +664 -0
  30. package/dist/note/extra-info.js +23 -0
  31. package/dist/note/images.js +100 -0
  32. package/dist/note/register.js +172 -0
  33. package/dist/note/sync-diff.js +143 -0
  34. package/dist/note/sync.js +748 -0
  35. package/dist/note/text-diff.js +71 -0
  36. package/dist/note/types.js +2 -0
  37. package/dist/recording/client.js +115 -0
  38. package/dist/recording/commands/config.js +73 -0
  39. package/dist/recording/commands/delete.js +171 -0
  40. package/dist/recording/commands/list.js +161 -0
  41. package/dist/recording/commands/shared.js +47 -0
  42. package/dist/recording/commands/transfer.js +192 -0
  43. package/dist/recording/commands/trash.js +140 -0
  44. package/dist/recording/config.js +104 -0
  45. package/dist/recording/dates.js +61 -0
  46. package/dist/recording/download.js +308 -0
  47. package/dist/recording/progress.js +77 -0
  48. package/dist/recording/pull.js +433 -0
  49. package/dist/recording/recording.js +294 -0
  50. package/dist/recording/register.js +202 -0
  51. package/dist/recording/template.js +44 -0
  52. package/dist/recording/types.js +2 -0
  53. package/package.json +53 -4
@@ -0,0 +1,100 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { basename, resolve } from "node:path";
3
+ import { listImageTargets, isLocalImageTarget, assertAttachmentsResolvable, } from "./converter.js";
4
+ /**
5
+ * 上传 Markdown 里引用的本地图片,返回可交给 markdownToXml 的 imageMap,
6
+ * 以及需要登记到笔记 setting.data 的附件(小米客户端靠它识别图片类型)。
7
+ *
8
+ * 先按「本地图片都能上传」做一次附件守护再真正上传,避免因其他问题中止时留下无用的上传。
9
+ *
10
+ * @param imageMap 已知引用 → fileId(如当前笔记已有附件)
11
+ * @param baseDirs 解析相对路径的基准目录,按顺序查找
12
+ */
13
+ export async function uploadLocalImages(client, markdown, imageMap, baseDirs) {
14
+ const pending = new Map();
15
+ for (const target of listImageTargets(markdown)) {
16
+ if (!isLocalImageTarget(target) || imageMap.has(target) || pending.has(target))
17
+ continue;
18
+ const path = await findLocalImage(target, baseDirs);
19
+ if (path)
20
+ pending.set(target, path);
21
+ }
22
+ const provisional = new Map(imageMap);
23
+ for (const target of pending.keys())
24
+ provisional.set(target, "pending");
25
+ assertAttachmentsResolvable(markdown, provisional);
26
+ const result = new Map(imageMap);
27
+ const uploaded = [];
28
+ const fileIdByPath = new Map();
29
+ for (const [target, path] of pending) {
30
+ let fileId = fileIdByPath.get(path);
31
+ if (!fileId) {
32
+ const mimeType = inferImageMimeType(path);
33
+ const buffer = new Uint8Array(await readFile(path));
34
+ const res = await client.uploadImage(buffer, { filename: basename(path), mimeType });
35
+ fileId = res.fileId;
36
+ fileIdByPath.set(path, fileId);
37
+ uploaded.push({ fileId, digest: res.digest, mimeType });
38
+ }
39
+ result.set(target, fileId);
40
+ }
41
+ return { imageMap: result, uploaded };
42
+ }
43
+ /** 把新上传的附件追加进 setting.data(已存在的 fileId 不重复登记) */
44
+ export function withAttachments(setting, uploaded) {
45
+ const base = setting ?? { themeId: 0, stickyTime: 0, version: 0 };
46
+ if (uploaded.length === 0)
47
+ return base;
48
+ const existing = base.data ?? [];
49
+ const known = new Set(existing.map((f) => f.fileId));
50
+ return {
51
+ ...base,
52
+ data: [...existing, ...uploaded.filter((f) => !known.has(f.fileId))],
53
+ };
54
+ }
55
+ /** 解析 Markdown 图片 target 为本地图片文件路径;不存在或不是图片时返回 undefined */
56
+ async function findLocalImage(target, baseDirs) {
57
+ // 去掉可选标题 `path "title"` 与尖括号 `<path with space>`
58
+ let raw = target.replace(/\s+"[^"]*"$/, "").trim();
59
+ if (raw.startsWith("<") && raw.endsWith(">"))
60
+ raw = raw.slice(1, -1);
61
+ const candidates = new Set([raw]);
62
+ try {
63
+ candidates.add(decodeURIComponent(raw));
64
+ }
65
+ catch {
66
+ // 非法百分号编码,按原样查找
67
+ }
68
+ for (const dir of baseDirs) {
69
+ for (const c of candidates) {
70
+ const path = resolve(dir, c);
71
+ if (!inferImageMimeType(path).startsWith("image/"))
72
+ continue;
73
+ try {
74
+ if ((await stat(path)).isFile())
75
+ return path;
76
+ }
77
+ catch {
78
+ // 不存在,继续找
79
+ }
80
+ }
81
+ }
82
+ return undefined;
83
+ }
84
+ /** 推断图片 MIME 类型 */
85
+ export function inferImageMimeType(filename) {
86
+ const lower = filename.toLowerCase();
87
+ if (lower.endsWith(".png"))
88
+ return "image/png";
89
+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg"))
90
+ return "image/jpeg";
91
+ if (lower.endsWith(".gif"))
92
+ return "image/gif";
93
+ if (lower.endsWith(".webp"))
94
+ return "image/webp";
95
+ if (lower.endsWith(".bmp"))
96
+ return "image/bmp";
97
+ if (lower.endsWith(".svg"))
98
+ return "image/svg+xml";
99
+ return "application/octet-stream";
100
+ }
@@ -0,0 +1,172 @@
1
+ import { listCommand } from "./commands/list.js";
2
+ import { getCommand } from "./commands/get.js";
3
+ import { searchCommand } from "./commands/search.js";
4
+ import { createCommand } from "./commands/create.js";
5
+ import { updateCommand } from "./commands/update.js";
6
+ import { deleteCommand } from "./commands/delete.js";
7
+ import { moveCommand } from "./commands/move.js";
8
+ import { pinCommand } from "./commands/pin.js";
9
+ import { foldersCommand, folderCreateCommand, folderRenameCommand, folderDeleteCommand, } from "./commands/folder.js";
10
+ import { uploadImageCommand } from "./commands/upload-image.js";
11
+ import { exportCommand } from "./commands/export.js";
12
+ import { syncCommand, syncInitCommand, syncStatusCommand } from "./commands/sync.js";
13
+ /** 注册 `micloud note` 命令组 */
14
+ export function registerNoteCommands(program) {
15
+ const note = program
16
+ .command("note")
17
+ .description("小米云笔记:读写、文件夹、图片、导出与双向同步")
18
+ .addHelpText("after", `
19
+ 笔记内容格式:
20
+ 读取(get)默认把小米笔记转成 Markdown;写入(create/update)接受 Markdown,自动转回小米格式。
21
+ 支持的 Markdown: 标题(# ## ###)、有序/无序列表、复选框(- [ ] / - [x])、引用(>)、
22
+ 分割线(---)、加粗(**)、斜体(*)、删除线(~~)、图片(![](minote://image/<fileId>))。
23
+
24
+ 典型流程:
25
+ 1) micloud note list --json # 列出笔记,拿到 <id>
26
+ 2) micloud note get <id> --json # 读取某条笔记
27
+ 3) micloud note create --title T --content "..." # 创建
28
+ 4) micloud note sync -o ./notes --mode two-way # 与本地目录双向同步
29
+
30
+ 破坏性操作(delete / sync 删除类)在非交互下需 -y 或由 --mode 决定,真冲突一律跳过不擅自删数据。
31
+ `);
32
+ // ============ 读 ============
33
+ note
34
+ .command("list")
35
+ .description("列出笔记")
36
+ .option("-f, --folder <id>", "仅列出指定文件夹下的笔记(id 来自 folders 命令)")
37
+ .option("-n, --limit <n>", "限制返回数量")
38
+ .action((opts) => listCommand(opts));
39
+ note
40
+ .command("get <id>")
41
+ .description("获取单条笔记内容(默认转 Markdown)")
42
+ .option("--raw", "输出原始 XML 内容")
43
+ .action((id, opts) => getCommand(id, opts))
44
+ .addHelpText("after", "\n <id> 来自 list / search 命令的输出。--json 时 data 含 id/title/content/files 等字段。\n");
45
+ note
46
+ .command("search <keyword>")
47
+ .description("按关键词搜索笔记标题与摘要")
48
+ .option("-n, --limit <n>", "限制返回数量(默认 20)")
49
+ .action((keyword, opts) => searchCommand(keyword, opts));
50
+ // ============ 写 ============
51
+ note
52
+ .command("create")
53
+ .description("创建笔记(内容来源:--content / --file / 标准输入)")
54
+ .option("-t, --title <title>", "笔记标题")
55
+ .option("-f, --folder <id>", "目标文件夹 ID(默认 0)")
56
+ .option("-c, --content <md>", "笔记内容(Markdown)")
57
+ .option("--file <path>", "从文件读取内容")
58
+ .option("--color <id>", "笔记颜色 ID")
59
+ .action((opts) => createCommand(opts))
60
+ .addHelpText("after", `
61
+ 示例:
62
+ micloud note create --title "标题" --content "# 正文\\n\\n- 列表项"
63
+ echo "# 来自管道" | micloud note create --title 管道笔记
64
+ micloud note create --file ./note.md --folder 123 --json
65
+ 插图:upload-image 后把 ![](minote://image/<fileId>) 放进内容;或直接写本地路径 ![](path.jpg) 自动上传。
66
+ --file 里的相对图片路径基于该文件所在目录;--content / 管道时基于当前目录。
67
+ `);
68
+ note
69
+ .command("update <id>")
70
+ .description("更新笔记(不提供内容则仅改元数据)")
71
+ .option("-t, --title <title>", "新标题")
72
+ .option("-f, --folder <id>", "移动到的文件夹 ID")
73
+ .option("-c, --content <md>", "新内容(Markdown)")
74
+ .option("--file <path>", "从文件读取新内容")
75
+ .option("--color <id>", "笔记颜色 ID")
76
+ .action((id, opts) => updateCommand(id, opts));
77
+ note
78
+ .command("delete <id>")
79
+ .description("删除笔记(默认移回收站,--purge 永久删除)")
80
+ .option("--purge", "永久删除(不可恢复)")
81
+ .option("-y, --yes", "跳过确认")
82
+ .action((id, opts) => deleteCommand(id, opts));
83
+ note
84
+ .command("move <id> <folderId>")
85
+ .description("将笔记移动到指定文件夹")
86
+ .action((id, folderId) => moveCommand(id, folderId));
87
+ note
88
+ .command("pin <id>")
89
+ .description("置顶笔记")
90
+ .action((id) => pinCommand(id, true));
91
+ note
92
+ .command("unpin <id>")
93
+ .description("取消置顶笔记")
94
+ .action((id) => pinCommand(id, false));
95
+ // ============ 文件夹 ============
96
+ note
97
+ .command("folders")
98
+ .description("列出所有文件夹")
99
+ .action(() => foldersCommand());
100
+ const folder = note.command("folder").description("文件夹管理(create / rename / delete)");
101
+ folder
102
+ .command("create <name>")
103
+ .description("创建文件夹")
104
+ .option("-p, --parent <id>", "父文件夹 ID(默认 0)")
105
+ .action((name, opts) => folderCreateCommand(name, opts));
106
+ folder
107
+ .command("rename <id> <name>")
108
+ .description("重命名文件夹")
109
+ .action((id, name) => folderRenameCommand(id, name));
110
+ folder
111
+ .command("delete <id>")
112
+ .description("删除文件夹")
113
+ .option("--purge", "永久删除")
114
+ .option("-y, --yes", "跳过确认")
115
+ .action((id, opts) => folderDeleteCommand(id, opts));
116
+ // ============ 图片 ============
117
+ note
118
+ .command("upload-image <path>")
119
+ .description("上传图片,返回可嵌入笔记的 fileId 与 Markdown 引用")
120
+ .option("--mime <type>", "图片 MIME 类型(默认自动推断)")
121
+ .option("--filename <name>", "上传时使用的文件名")
122
+ .action((path, opts) => uploadImageCommand(path, opts));
123
+ // ============ 导出/同步 ============
124
+ note
125
+ .command("export")
126
+ .description("导出全部笔记为本地 Markdown(单向云→本地,永不修改云端)")
127
+ .option("-o, --output <dir>", "输出目录(缺省时取配置的 output;再缺省为 .micloud/note/,旧版默认目录 .mi-note-cli/output/ 存在时沿用它)")
128
+ .option("-f, --force", "强制重新导出(忽略本地已有同名文件)")
129
+ .addHelpText("after", `
130
+ 与 sync --mode cloud-first 的区别:
131
+ export 无状态文件、不删本地文件(云端删了本地保留)、支持 --force 全量重下。
132
+ 适合一次性备份/快照;需要持续同步用 sync。
133
+ `)
134
+ .action((opts) => exportCommand(opts));
135
+ const sync = note
136
+ .command("sync")
137
+ .description("双向同步本地与云端(3-way 差异 + 模式策略)")
138
+ .option("-o, --output <dir>", "同步目录(缺省时取配置的 output;再缺省为 .micloud/note/,旧版默认目录 .mi-note-cli/output/ 存在时沿用它)")
139
+ .option("-m, --mode <mode>", "同步模式:cloud-first/local-first/two-way/manual")
140
+ .option("--dry-run", "只列出同步计划,不实际执行")
141
+ .option("-y, --yes", "跳过交互询问(非交互按模式处理,真冲突跳过)")
142
+ .action((opts) => syncCommand(opts))
143
+ .addHelpText("after", `
144
+ 同步模式 (--mode,未指定时取 sync init 设的默认值,再缺省为 manual):
145
+ cloud-first 云端优先:仅下行,冲突以云端为准
146
+ local-first 本地优先:仅上行,冲突以本地为准
147
+ two-way 双向自动:单边改自动同步,真冲突才停下询问
148
+ manual 交互(默认):任何不一致都列出并逐条询问
149
+
150
+ 冲突处理:
151
+ cloud-first/local-first 已声明优先方,冲突按优先方自动解决;
152
+ two-way/manual 遇到「双改」「一端删另一端改」等真冲突会停下:交互式询问,
153
+ 非交互(--json/无 TTY)则跳过该条并在结果里报告,绝不擅自删数据。
154
+ 交互询问时可按 d 查看云端与本地的差异。同步删除云端笔记只移到回收站。
155
+
156
+ 示例:
157
+ micloud note sync -o ./notes --dry-run # 预览将发生什么
158
+ micloud note sync -o ./notes --mode two-way # 双向同步
159
+ micloud note sync init # 引导设置默认模式
160
+ micloud note sync status # 查看配置与状态
161
+ `);
162
+ sync
163
+ .command("init")
164
+ .description("交互式引导设置默认同步模式")
165
+ .action(() => syncInitCommand());
166
+ sync
167
+ .command("status")
168
+ .description("查看配置与当前 output 的同步状态")
169
+ .option("-o, --output <dir>", "查看指定目录的状态(缺省同 sync)")
170
+ // `-o` 写在 status 后面时会先被上层 sync 命令解析走,合并上层选项才能拿到
171
+ .action((_opts, cmd) => syncStatusCommand(cmd.optsWithGlobals()));
172
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 判定三方差异属于哪个场景。
3
+ */
4
+ export function classify(input) {
5
+ const { baseHash, remoteHash, localHash } = input;
6
+ const hasBase = baseHash !== undefined;
7
+ const hasRemote = remoteHash !== undefined;
8
+ const hasLocal = localHash !== undefined;
9
+ // 无基线:本次是新关系
10
+ if (!hasBase) {
11
+ if (hasRemote && !hasLocal)
12
+ return "remote-new"; // #5
13
+ if (!hasRemote && hasLocal)
14
+ return "local-new"; // #6
15
+ if (hasRemote && hasLocal) {
16
+ // 两端都新出现:内容相同视为已同步,不同视为双改冲突
17
+ return remoteHash === localHash ? "in-sync" : "both-changed";
18
+ }
19
+ return "in-sync"; // 三方皆无,理论上不会发生
20
+ }
21
+ // 有基线
22
+ const remoteChanged = hasRemote && remoteHash !== baseHash;
23
+ const localChanged = hasLocal && localHash !== baseHash;
24
+ // 删除判定(相对基线消失)
25
+ if (!hasRemote && !hasLocal)
26
+ return "both-deleted"; // #11
27
+ if (!hasRemote && hasLocal) {
28
+ return localChanged
29
+ ? "remote-deleted-local-changed" // #8
30
+ : "remote-deleted-local-clean"; // #7
31
+ }
32
+ if (hasRemote && !hasLocal) {
33
+ return remoteChanged
34
+ ? "local-deleted-remote-changed" // #10
35
+ : "local-deleted-remote-clean"; // #9
36
+ }
37
+ // 两端都存在
38
+ if (!remoteChanged && !localChanged)
39
+ return "in-sync"; // #1
40
+ if (remoteChanged && !localChanged)
41
+ return "remote-changed"; // #2
42
+ if (!remoteChanged && localChanged)
43
+ return "local-changed"; // #3
44
+ // 两端都相对基线变了:若变成相同内容则已自然一致,否则才是双改冲突
45
+ return remoteHash === localHash ? "in-sync" : "both-changed"; // #4
46
+ }
47
+ /**
48
+ * 给定场景 + 模式,决定要执行的动作。
49
+ *
50
+ * 设计要点:
51
+ * - 非冲突场景(#2/#3/#5/#6/#7/#9)方向明确,按 mode 的"是否允许下行/上行/删除"裁剪。
52
+ * - 冲突场景(#4/#8/#10):有明确优先方的 mode(cloud-first/local-first)按优先方解决;
53
+ * manual / two-way 返回 `conflict`,交由调用方处理(交互询问或非交互跳过报告)。
54
+ */
55
+ export function decide(scenario, mode) {
56
+ switch (scenario) {
57
+ case "in-sync":
58
+ return "skip";
59
+ case "remote-changed": // #2 仅云端改
60
+ // 除 local-first(本地优先、忽略云端变更)外都下行
61
+ return mode === "local-first" ? "skip" : "update-local";
62
+ case "local-changed": // #3 仅本地改
63
+ // 只有会上行的模式才更新云端
64
+ return mode === "local-first" || mode === "two-way"
65
+ ? "update-remote"
66
+ : mode === "manual"
67
+ ? "conflict" // manual 任何不一致都问
68
+ : "skip"; // cloud-first 不上行
69
+ case "remote-new": // #5 云端新增
70
+ return mode === "local-first" ? "skip" : "create-local";
71
+ case "local-new": // #6 本地新增
72
+ return mode === "local-first" || mode === "two-way"
73
+ ? "create-remote"
74
+ : mode === "manual"
75
+ ? "conflict"
76
+ : "skip"; // cloud-first 不上行
77
+ case "remote-deleted-local-clean": // #7 云删本地未改
78
+ // 删本地以跟随云端;local-first 模式视本地为权威,反而重建云端
79
+ if (mode === "local-first")
80
+ return "create-remote";
81
+ if (mode === "manual")
82
+ return "conflict";
83
+ return "delete-local";
84
+ case "local-deleted-remote-clean": // #9 本地删云未改
85
+ // 删云端以跟随本地;cloud-first 视云端为权威,反而重建本地
86
+ if (mode === "cloud-first")
87
+ return "create-local";
88
+ if (mode === "manual")
89
+ return "conflict";
90
+ return "delete-remote"; // local-first / two-way
91
+ case "both-deleted": // #11
92
+ return "drop-state";
93
+ // ---- 真冲突场景 ----
94
+ case "both-changed": // #4 双改
95
+ case "remote-deleted-local-changed": // #8 云删本地改
96
+ case "local-deleted-remote-changed": // #10 本地删云改
97
+ return resolveConflict(scenario, mode);
98
+ default:
99
+ return "skip";
100
+ }
101
+ }
102
+ /**
103
+ * 冲突场景的解决:有明确优先方的 mode 直接裁决;manual/two-way 交回 conflict。
104
+ */
105
+ function resolveConflict(scenario, mode) {
106
+ switch (mode) {
107
+ case "cloud-first":
108
+ return actionForSide(scenario, "remote");
109
+ case "local-first":
110
+ return actionForSide(scenario, "local");
111
+ case "two-way":
112
+ case "manual":
113
+ default:
114
+ return "conflict"; // 交由调用方:交互询问或非交互跳过报告
115
+ }
116
+ }
117
+ const LOCAL_WINS = {
118
+ "local-changed": "update-remote",
119
+ "both-changed": "update-remote",
120
+ "local-new": "create-remote",
121
+ // 云端已删:本地为准只能在云端重建
122
+ "remote-deleted-local-clean": "create-remote",
123
+ "remote-deleted-local-changed": "create-remote",
124
+ "local-deleted-remote-clean": "delete-remote",
125
+ "local-deleted-remote-changed": "delete-remote",
126
+ };
127
+ const REMOTE_WINS = {
128
+ "remote-changed": "update-local",
129
+ "both-changed": "update-local",
130
+ "remote-new": "create-local",
131
+ "local-deleted-remote-clean": "create-local",
132
+ "local-deleted-remote-changed": "update-local",
133
+ "remote-deleted-local-clean": "delete-local",
134
+ "remote-deleted-local-changed": "delete-local",
135
+ };
136
+ /**
137
+ * 以某一侧为准时该场景应执行的动作;该侧没有可传播的内容时返回 skip
138
+ * (例如本地新增文件「以云端为准」不删本地,只是不上传)。
139
+ */
140
+ export function actionForSide(scenario, side) {
141
+ const table = side === "local" ? LOCAL_WINS : REMOTE_WINS;
142
+ return table[scenario] ?? "skip";
143
+ }