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,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一输出层:支持人类可读输出与 --json 机器可读输出。
|
|
3
|
+
*
|
|
4
|
+
* 设计约定:
|
|
5
|
+
* - 所有结构化结果走 stdout(JSON 模式输出纯 JSON,便于 AI/管道解析)。
|
|
6
|
+
* - 所有日志、进度、提示走 stderr(不污染 stdout 结果)。
|
|
7
|
+
*/
|
|
8
|
+
let jsonMode = false;
|
|
9
|
+
export function setJsonMode(enabled) {
|
|
10
|
+
jsonMode = enabled;
|
|
11
|
+
}
|
|
12
|
+
export function isJsonMode() {
|
|
13
|
+
return jsonMode;
|
|
14
|
+
}
|
|
15
|
+
/** 输出一条日志/进度到 stderr */
|
|
16
|
+
export function logInfo(message) {
|
|
17
|
+
process.stderr.write(message + "\n");
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 输出成功结果。
|
|
21
|
+
* - JSON 模式:输出 { ok: true, data }
|
|
22
|
+
* - 普通模式:调用 humanRender 渲染
|
|
23
|
+
*/
|
|
24
|
+
export function success(data, humanRender) {
|
|
25
|
+
if (jsonMode) {
|
|
26
|
+
process.stdout.write(JSON.stringify({ ok: true, data }, null, 2) + "\n");
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
humanRender();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** 输出纯文本结果(如笔记 Markdown 内容),JSON 模式下包进 data */
|
|
33
|
+
export function output(text, jsonKey = "content") {
|
|
34
|
+
if (jsonMode) {
|
|
35
|
+
process.stdout.write(JSON.stringify({ ok: true, data: { [jsonKey]: text } }, null, 2) + "\n");
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
process.stdout.write(text + "\n");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** 输出错误并以非零码退出 */
|
|
42
|
+
export function fail(error) {
|
|
43
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
44
|
+
if (jsonMode) {
|
|
45
|
+
process.stdout.write(JSON.stringify({ ok: false, error: message }, null, 2) + "\n");
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
process.stderr.write(`❌ ${message}\n`);
|
|
49
|
+
}
|
|
50
|
+
process.exit(1);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* 部分条目失败时的退出码:结果仍按 ok:true 输出(失败项列在 data 里),
|
|
54
|
+
* 但以非零码退出,便于脚本用 `&&` / `$?` 感知。整体失败退出码为 1。
|
|
55
|
+
*/
|
|
56
|
+
export const EXIT_PARTIAL_FAILURE = 2;
|
|
57
|
+
/**
|
|
58
|
+
* 输出批量操作的结果,并按「成功 / 部分失败 / 全部失败」设置退出码:
|
|
59
|
+
* - 没有失败:ok:true,退出码 0;
|
|
60
|
+
* - 部分失败(或有警告):ok:true,退出码 2;
|
|
61
|
+
* - 有失败且一条都没成功:ok:false,退出码 1,error 取首条失败原因,data 照常附带明细。
|
|
62
|
+
* 只设置 process.exitCode,不立即退出,调用方的 finally(如释放目录锁)照常执行。
|
|
63
|
+
*/
|
|
64
|
+
export function finishBatch(data, outcome, humanRender) {
|
|
65
|
+
const failedCount = outcome.failed.length;
|
|
66
|
+
if (failedCount > 0 && outcome.succeeded === 0) {
|
|
67
|
+
const first = outcome.failed[0].error;
|
|
68
|
+
const error = failedCount === 1 ? first : `全部 ${failedCount} 条失败,首条原因:${first}`;
|
|
69
|
+
if (jsonMode) {
|
|
70
|
+
process.stdout.write(JSON.stringify({ ok: false, error, data }, null, 2) + "\n");
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
humanRender();
|
|
74
|
+
}
|
|
75
|
+
process.exitCode = 1;
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
success(data, humanRender);
|
|
79
|
+
if (failedCount > 0 || (outcome.warnings ?? 0) > 0)
|
|
80
|
+
process.exitCode = EXIT_PARTIAL_FAILURE;
|
|
81
|
+
}
|
|
82
|
+
/** 是否可以向用户提问(非 JSON 模式且 stdin 是终端) */
|
|
83
|
+
export function canPrompt() {
|
|
84
|
+
return !jsonMode && !!process.stdin.isTTY;
|
|
85
|
+
}
|
|
86
|
+
/** 读取一行用户输入(问题走 stderr,不污染 stdout) */
|
|
87
|
+
export function prompt(question) {
|
|
88
|
+
return new Promise((resolve) => {
|
|
89
|
+
process.stderr.write(question);
|
|
90
|
+
const stdin = process.stdin;
|
|
91
|
+
stdin.setEncoding("utf-8");
|
|
92
|
+
const onData = (data) => {
|
|
93
|
+
stdin.pause();
|
|
94
|
+
stdin.off("data", onData);
|
|
95
|
+
resolve(data.trim());
|
|
96
|
+
};
|
|
97
|
+
stdin.resume();
|
|
98
|
+
stdin.on("data", onData);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/** 命令行 y/N 确认提示 */
|
|
102
|
+
export async function confirm(question) {
|
|
103
|
+
return (await prompt(question)).toLowerCase() === "y";
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* 破坏性操作在非交互模式(--json / 无终端)下必须带 -y:没带就立即报错。
|
|
107
|
+
* 在发起任何请求之前调用,让 AI / 脚本第一时间拿到明确错误,也不会卡在等待输入上。
|
|
108
|
+
*/
|
|
109
|
+
export function assertCanConfirm(yes) {
|
|
110
|
+
if (!yes && !canPrompt()) {
|
|
111
|
+
throw new Error("这是破坏性操作,非交互模式(--json / 无终端)下需加 -y 明确确认");
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* 破坏性操作的确认:带 -y 直接通过;能交互时 y/N 询问;
|
|
116
|
+
* 非交互(--json / 无终端)且未带 -y 时直接报错,绝不擅自执行。
|
|
117
|
+
*/
|
|
118
|
+
export async function confirmDestructive(question, yes) {
|
|
119
|
+
if (yes)
|
|
120
|
+
return true;
|
|
121
|
+
assertCanConfirm(yes);
|
|
122
|
+
return await confirm(`${question} (y/N) `);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* 从 stdin 读取全部输入(用于从管道接收内容)。
|
|
126
|
+
* 若 stdin 是 TTY(无管道输入)返回 null。
|
|
127
|
+
*/
|
|
128
|
+
export async function readStdin() {
|
|
129
|
+
if (process.stdin.isTTY)
|
|
130
|
+
return null;
|
|
131
|
+
const chunks = [];
|
|
132
|
+
for await (const chunk of process.stdin) {
|
|
133
|
+
chunks.push(chunk);
|
|
134
|
+
}
|
|
135
|
+
const text = Buffer.concat(chunks).toString("utf-8");
|
|
136
|
+
return text.length > 0 ? text : null;
|
|
137
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { getDateTokens } from "./utils.js";
|
|
2
|
+
/**
|
|
3
|
+
* 文件名模板引擎(笔记与录音共用;可用的变量由各服务提供)。
|
|
4
|
+
*
|
|
5
|
+
* - `${var}` 替换为 vars 中的值;未识别的变量原样保留
|
|
6
|
+
* - 条件段 `[...]`:段内所有已知 `${var}` 都非空才渲染,否则整段(含分隔符)丢弃;不支持嵌套;
|
|
7
|
+
* 未闭合的 `[` 按字面保留;字面 `[` `]` 用 `\[` `\]`
|
|
8
|
+
* - transform 用于加工替换进来的变量值(如把值里的 `/` 换掉,避免被当成目录分隔符)
|
|
9
|
+
*
|
|
10
|
+
* 不做文件名清理,调用方按需 sanitize。
|
|
11
|
+
*/
|
|
12
|
+
export function renderTemplate(template, vars, transform = (v) => v) {
|
|
13
|
+
// 用 NUL/SOH 哨兵临时替换 `\[` `\]` 转义,避免被条件段解析器误吞(这两个控制字符不会出现在模板里)
|
|
14
|
+
const ESC_OPEN = "\u0000";
|
|
15
|
+
const ESC_CLOSE = "\u0001";
|
|
16
|
+
const lookup = (key) => Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : undefined;
|
|
17
|
+
let s = template.replace(/\\\[/g, ESC_OPEN).replace(/\\\]/g, ESC_CLOSE);
|
|
18
|
+
s = s.replace(/\[([^\[\]]*)\]/g, (_, segment) => {
|
|
19
|
+
let allFilled = true;
|
|
20
|
+
const rendered = segment.replace(/\$\{(\w+)\}/g, (m, key) => {
|
|
21
|
+
const v = lookup(key);
|
|
22
|
+
if (v === undefined)
|
|
23
|
+
return m;
|
|
24
|
+
if (!v)
|
|
25
|
+
allFilled = false;
|
|
26
|
+
return transform(v);
|
|
27
|
+
});
|
|
28
|
+
return allFilled ? rendered : "";
|
|
29
|
+
});
|
|
30
|
+
s = s.replace(/\$\{(\w+)\}/g, (m, key) => {
|
|
31
|
+
const v = lookup(key);
|
|
32
|
+
return v === undefined ? m : transform(v);
|
|
33
|
+
});
|
|
34
|
+
return s.replace(new RegExp(ESC_OPEN, "g"), "[").replace(new RegExp(ESC_CLOSE, "g"), "]");
|
|
35
|
+
}
|
|
36
|
+
/** 时间占位符 `${YYYY}` `${YY}` `${MM}` `${DD}` `${HH}` `${mm}` `${ss}`(本地时区) */
|
|
37
|
+
export function dateVars(ts) {
|
|
38
|
+
return { ...getDateTokens(ts) };
|
|
39
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir, access, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { homedir, platform } from "node:os";
|
|
5
|
+
export const APP_NAME = "micloud";
|
|
6
|
+
/** 文件名主体的最大 UTF-8 字节数(留出 `_<id>` 后缀与扩展名的空间,整体不超过常见文件系统的 255 字节上限) */
|
|
7
|
+
const MAX_NAME_BYTES = 200;
|
|
8
|
+
/** 清理文件名中的非法字符,并按 UTF-8 字节截断;Windows 保留设备名(CON、NUL、COM1 等)前加 `_` */
|
|
9
|
+
export function sanitizeFileName(name) {
|
|
10
|
+
const cleaned = name
|
|
11
|
+
.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_")
|
|
12
|
+
.replace(/\s+/g, " ")
|
|
13
|
+
.trim()
|
|
14
|
+
.replace(/^\.+/, "")
|
|
15
|
+
.replace(/[.\s]+$/, "")
|
|
16
|
+
.trim();
|
|
17
|
+
const truncated = truncateUtf8(cleaned, MAX_NAME_BYTES).replace(/[.\s]+$/, "");
|
|
18
|
+
return /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(truncated) ? `_${truncated}` : truncated;
|
|
19
|
+
}
|
|
20
|
+
/** 按 UTF-8 字节数截断,不切断多字节字符 */
|
|
21
|
+
export function truncateUtf8(text, maxBytes) {
|
|
22
|
+
if (Buffer.byteLength(text) <= maxBytes)
|
|
23
|
+
return text;
|
|
24
|
+
let bytes = 0;
|
|
25
|
+
let out = "";
|
|
26
|
+
for (const ch of text) {
|
|
27
|
+
const size = Buffer.byteLength(ch);
|
|
28
|
+
if (bytes + size > maxBytes)
|
|
29
|
+
break;
|
|
30
|
+
bytes += size;
|
|
31
|
+
out += ch;
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
/** 延时 */
|
|
36
|
+
export function delay(ms) {
|
|
37
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
38
|
+
}
|
|
39
|
+
/** 带随机抖动的延时(模拟人类节奏,降低风控概率) */
|
|
40
|
+
export function randomDelay(baseMs, jitterRatio = 0.5) {
|
|
41
|
+
const jitter = baseMs * jitterRatio * (2 * Math.random() - 1);
|
|
42
|
+
return delay(Math.max(50, Math.round(baseMs + jitter)));
|
|
43
|
+
}
|
|
44
|
+
/** 把时间戳拆为本地时区的零填充分量 */
|
|
45
|
+
export function getDateTokens(ts) {
|
|
46
|
+
const d = new Date(ts);
|
|
47
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
48
|
+
const yyyy = String(d.getFullYear());
|
|
49
|
+
return {
|
|
50
|
+
YYYY: yyyy,
|
|
51
|
+
YY: yyyy.slice(-2),
|
|
52
|
+
MM: pad(d.getMonth() + 1),
|
|
53
|
+
DD: pad(d.getDate()),
|
|
54
|
+
HH: pad(d.getHours()),
|
|
55
|
+
mm: pad(d.getMinutes()),
|
|
56
|
+
ss: pad(d.getSeconds()),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
/** 格式化为 YYYY-MM-DD_HH-mm-ss(可用作文件名) */
|
|
60
|
+
export function formatDateTime(ts) {
|
|
61
|
+
const t = getDateTokens(ts);
|
|
62
|
+
return `${t.YYYY}-${t.MM}-${t.DD}_${t.HH}-${t.mm}-${t.ss}`;
|
|
63
|
+
}
|
|
64
|
+
/** 本地时间显示:`2026-07-02 16:04`(withSeconds 时带秒) */
|
|
65
|
+
export function formatTime(ts, withSeconds = false) {
|
|
66
|
+
if (!ts)
|
|
67
|
+
return "";
|
|
68
|
+
const t = getDateTokens(ts);
|
|
69
|
+
const base = `${t.YYYY}-${t.MM}-${t.DD} ${t.HH}:${t.mm}`;
|
|
70
|
+
return withSeconds ? `${base}:${t.ss}` : base;
|
|
71
|
+
}
|
|
72
|
+
/** 字节数转可读体积:`45.2 MB` */
|
|
73
|
+
export function formatBytes(bytes) {
|
|
74
|
+
if (!Number.isFinite(bytes) || bytes < 1024)
|
|
75
|
+
return `${Math.max(0, Math.round(bytes || 0))} B`;
|
|
76
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
77
|
+
let value = bytes / 1024;
|
|
78
|
+
let i = 0;
|
|
79
|
+
while (value >= 1024 && i < units.length - 1) {
|
|
80
|
+
value /= 1024;
|
|
81
|
+
i++;
|
|
82
|
+
}
|
|
83
|
+
return `${value.toFixed(value < 10 ? 2 : 1)} ${units[i]}`;
|
|
84
|
+
}
|
|
85
|
+
/** 秒数转时长:`3:05` / `1:02:03` */
|
|
86
|
+
export function formatDuration(seconds) {
|
|
87
|
+
const total = Math.max(0, Math.round(seconds || 0));
|
|
88
|
+
const h = Math.floor(total / 3600);
|
|
89
|
+
const m = Math.floor((total % 3600) / 60);
|
|
90
|
+
const s = total % 60;
|
|
91
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
92
|
+
return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`;
|
|
93
|
+
}
|
|
94
|
+
/** 确保目录存在 */
|
|
95
|
+
export async function ensureDir(dirPath) {
|
|
96
|
+
await mkdir(dirPath, { recursive: true });
|
|
97
|
+
}
|
|
98
|
+
/** 检查文件是否存在 */
|
|
99
|
+
export async function fileExists(filePath) {
|
|
100
|
+
try {
|
|
101
|
+
await access(filePath);
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** 确保文件所在目录存在 */
|
|
109
|
+
export async function ensureFileDir(filePath) {
|
|
110
|
+
await ensureDir(dirname(filePath));
|
|
111
|
+
}
|
|
112
|
+
/** 原子写文件:先写同目录临时文件再改名,进程中断也不会留下半截内容 */
|
|
113
|
+
export async function writeFileAtomic(filePath, content) {
|
|
114
|
+
await ensureFileDir(filePath);
|
|
115
|
+
const tmp = `${filePath}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
|
|
116
|
+
await writeFile(tmp, content, "utf-8");
|
|
117
|
+
await rename(tmp, filePath);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* 全局缓存目录(跨平台)——只放登录状态等可重建的缓存。
|
|
121
|
+
*
|
|
122
|
+
* - macOS: ~/Library/Caches/micloud/
|
|
123
|
+
* - Linux: $XDG_CACHE_HOME/micloud/ 或 ~/.cache/micloud/
|
|
124
|
+
* - Windows: %LOCALAPPDATA%/micloud/cache/
|
|
125
|
+
*
|
|
126
|
+
* `MICLOUD_CACHE_DIR` 可覆盖(测试隔离用)。
|
|
127
|
+
*/
|
|
128
|
+
export function getCacheDir() {
|
|
129
|
+
return process.env.MICLOUD_CACHE_DIR || platformCacheDir(APP_NAME);
|
|
130
|
+
}
|
|
131
|
+
/** 旧版工具(如 mi-note-cli)的缓存目录,只用于首次使用时沿用其登录状态 */
|
|
132
|
+
export function getLegacyCacheDir(app) {
|
|
133
|
+
return platformCacheDir(app);
|
|
134
|
+
}
|
|
135
|
+
function platformCacheDir(app) {
|
|
136
|
+
const home = homedir();
|
|
137
|
+
switch (platform()) {
|
|
138
|
+
case "darwin":
|
|
139
|
+
return join(home, "Library", "Caches", app);
|
|
140
|
+
case "win32":
|
|
141
|
+
return join(process.env.LOCALAPPDATA || join(home, "AppData", "Local"), app, "cache");
|
|
142
|
+
default:
|
|
143
|
+
return join(process.env.XDG_CACHE_HOME || join(home, ".cache"), app);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
/** 解析正整数参数;未提供时返回 fallback */
|
|
147
|
+
export function parsePositiveInt(raw, fallback, name) {
|
|
148
|
+
if (raw === undefined)
|
|
149
|
+
return fallback;
|
|
150
|
+
const n = Number(raw);
|
|
151
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
152
|
+
throw new Error(`${name} 必须是正整数,收到:${raw}`);
|
|
153
|
+
}
|
|
154
|
+
return n;
|
|
155
|
+
}
|
|
156
|
+
// ============ 终端显示宽度(CJK 记 2 列) ============
|
|
157
|
+
/** 字符串在终端中的显示宽度 */
|
|
158
|
+
export function displayWidth(text) {
|
|
159
|
+
let width = 0;
|
|
160
|
+
for (const ch of text)
|
|
161
|
+
width += isWide(ch) ? 2 : 1;
|
|
162
|
+
return width;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 按显示宽度截断字符串,超出加省略号。
|
|
166
|
+
* 同时把内部换行/连续空白压成单空格,保证终端列表每条只占一行。
|
|
167
|
+
*/
|
|
168
|
+
export function truncateDisplay(text, maxWidth) {
|
|
169
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
170
|
+
let width = 0;
|
|
171
|
+
let out = "";
|
|
172
|
+
for (const ch of flat) {
|
|
173
|
+
const w = isWide(ch) ? 2 : 1;
|
|
174
|
+
if (width + w > maxWidth)
|
|
175
|
+
return out + "…";
|
|
176
|
+
width += w;
|
|
177
|
+
out += ch;
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
/** 右侧补空格到指定显示宽度 */
|
|
182
|
+
export function padEndDisplay(text, width) {
|
|
183
|
+
return text + " ".repeat(Math.max(0, width - displayWidth(text)));
|
|
184
|
+
}
|
|
185
|
+
/** 左侧补空格到指定显示宽度 */
|
|
186
|
+
export function padStartDisplay(text, width) {
|
|
187
|
+
return " ".repeat(Math.max(0, width - displayWidth(text))) + text;
|
|
188
|
+
}
|
|
189
|
+
/** 判断字符是否为宽字符(CJK、全角等占 2 列) */
|
|
190
|
+
function isWide(ch) {
|
|
191
|
+
const cp = ch.codePointAt(0) ?? 0;
|
|
192
|
+
return ((cp >= 0x1100 && cp <= 0x115f) || // Hangul Jamo
|
|
193
|
+
(cp >= 0x2e80 && cp <= 0x303e) || // CJK 部首、标点
|
|
194
|
+
(cp >= 0x3041 && cp <= 0x33ff) || // 假名、CJK 符号
|
|
195
|
+
(cp >= 0x3400 && cp <= 0x4dbf) || // CJK 扩展 A
|
|
196
|
+
(cp >= 0x4e00 && cp <= 0x9fff) || // CJK 统一表意
|
|
197
|
+
(cp >= 0xa000 && cp <= 0xa4cf) || // 彝文
|
|
198
|
+
(cp >= 0xac00 && cp <= 0xd7a3) || // 谚文音节
|
|
199
|
+
(cp >= 0xf900 && cp <= 0xfaff) || // CJK 兼容表意
|
|
200
|
+
(cp >= 0xfe30 && cp <= 0xfe4f) || // CJK 兼容形式
|
|
201
|
+
(cp >= 0xff00 && cp <= 0xff60) || // 全角 ASCII
|
|
202
|
+
(cp >= 0xffe0 && cp <= 0xffe6) || // 全角符号
|
|
203
|
+
(cp >= 0x20000 && cp <= 0x3fffd) // CJK 扩展 B+及表情等
|
|
204
|
+
);
|
|
205
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { writeFile } from "node:fs/promises";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { MiCloudHttp, AuthExpiredError, API_BASE } from "../core/http.js";
|
|
4
|
+
import { fileExists, ensureFileDir, delay, randomDelay } from "../core/utils.js";
|
|
5
|
+
/**
|
|
6
|
+
* 小米云笔记 API 客户端:封装全部读/写/上传/下载操作。
|
|
7
|
+
*
|
|
8
|
+
* 写操作统一为 POST + application/x-www-form-urlencoded,body 携带 serviceToken。
|
|
9
|
+
* 更新/删除遵循乐观锁:先 GET 拿最新 tag,再提交。
|
|
10
|
+
*
|
|
11
|
+
* 登录态续期、超时与只读请求的重试由 MiCloudHttp 负责。
|
|
12
|
+
*/
|
|
13
|
+
export class MiNoteClient {
|
|
14
|
+
http;
|
|
15
|
+
constructor(auth, refresher) {
|
|
16
|
+
this.http = new MiCloudHttp(auth, refresher, `${API_BASE}/note/h5`);
|
|
17
|
+
}
|
|
18
|
+
// ============ 读操作 ============
|
|
19
|
+
/** 获取笔记列表(单页) */
|
|
20
|
+
async fetchPage(limit = 200, syncTag = "") {
|
|
21
|
+
const query = { limit: String(limit) };
|
|
22
|
+
if (syncTag)
|
|
23
|
+
query.syncTag = syncTag;
|
|
24
|
+
const json = await this.http.getJson("/note/full/page/", query);
|
|
25
|
+
if (json.result !== "ok" || !json.data) {
|
|
26
|
+
throw new Error(`获取笔记列表失败: ${JSON.stringify(json)}`);
|
|
27
|
+
}
|
|
28
|
+
return json.data;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* 获取全部笔记(自动分页)。
|
|
32
|
+
* @param onProgress 进度回调(已获取条数)
|
|
33
|
+
*/
|
|
34
|
+
async getAllNotes(limit = 200, onProgress) {
|
|
35
|
+
let syncTag = "";
|
|
36
|
+
const allEntries = [];
|
|
37
|
+
const allFolders = {};
|
|
38
|
+
while (true) {
|
|
39
|
+
const data = await this.fetchPage(limit, syncTag);
|
|
40
|
+
const entries = data.entries ?? [];
|
|
41
|
+
const folders = data.folders ?? [];
|
|
42
|
+
allEntries.push(...entries);
|
|
43
|
+
for (const folder of folders) {
|
|
44
|
+
allFolders[String(folder.id)] = folder;
|
|
45
|
+
}
|
|
46
|
+
onProgress?.(allEntries.length);
|
|
47
|
+
syncTag = data.syncTag ?? syncTag;
|
|
48
|
+
if (data.lastPage)
|
|
49
|
+
break;
|
|
50
|
+
if (!syncTag)
|
|
51
|
+
break;
|
|
52
|
+
await randomDelay(300);
|
|
53
|
+
}
|
|
54
|
+
return { entries: allEntries, folders: allFolders, syncTag };
|
|
55
|
+
}
|
|
56
|
+
/** 获取笔记详情 */
|
|
57
|
+
async getNote(noteId) {
|
|
58
|
+
const json = await this.http.getJson(`/note/note/${encodeURIComponent(String(noteId))}/`);
|
|
59
|
+
if (json.result !== "ok" || !json.data?.entry) {
|
|
60
|
+
throw new Error(`获取笔记详情失败: ${noteId}`);
|
|
61
|
+
}
|
|
62
|
+
return json.data.entry;
|
|
63
|
+
}
|
|
64
|
+
// ============ 写操作:笔记 ============
|
|
65
|
+
/** 创建笔记 */
|
|
66
|
+
async createNote(entry) {
|
|
67
|
+
const json = await this.http.postForm("/note/note", {
|
|
68
|
+
entry: JSON.stringify(entry),
|
|
69
|
+
});
|
|
70
|
+
if (json.result !== "ok" || !json.data?.entry) {
|
|
71
|
+
throw new Error(`创建笔记失败: ${json.description ?? JSON.stringify(json)}`);
|
|
72
|
+
}
|
|
73
|
+
return json.data.entry;
|
|
74
|
+
}
|
|
75
|
+
/** 更新笔记 */
|
|
76
|
+
async updateNote(noteId, entry) {
|
|
77
|
+
const json = await this.http.postForm(`/note/note/${encodeURIComponent(noteId)}`, {
|
|
78
|
+
entry: JSON.stringify(entry),
|
|
79
|
+
});
|
|
80
|
+
if (json.result !== "ok") {
|
|
81
|
+
throw new Error(`更新笔记失败: ${json.description ?? JSON.stringify(json)}`);
|
|
82
|
+
}
|
|
83
|
+
return json.data?.entry ?? entry;
|
|
84
|
+
}
|
|
85
|
+
/** 删除笔记(默认移到回收站;purge=true 永久删除) */
|
|
86
|
+
async deleteNote(noteId, tag, purge = false) {
|
|
87
|
+
let noteTag = tag;
|
|
88
|
+
if (!noteTag) {
|
|
89
|
+
const entry = await this.getNote(noteId);
|
|
90
|
+
noteTag = entry.tag;
|
|
91
|
+
if (!noteTag)
|
|
92
|
+
throw new Error("笔记详情中未找到 tag,无法删除");
|
|
93
|
+
}
|
|
94
|
+
await this.deleteEntity(noteId, noteTag, purge);
|
|
95
|
+
}
|
|
96
|
+
// ============ 写操作:文件夹 ============
|
|
97
|
+
/** 创建文件夹 */
|
|
98
|
+
async createFolder(subject, parentId = "0") {
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
const entry = {
|
|
101
|
+
subject,
|
|
102
|
+
folderId: parentId,
|
|
103
|
+
createDate: now,
|
|
104
|
+
modifyDate: now,
|
|
105
|
+
colorId: 0,
|
|
106
|
+
alertDate: 0,
|
|
107
|
+
alertTag: 0,
|
|
108
|
+
type: "folder",
|
|
109
|
+
setting: { themeId: 0, stickyTime: 0, version: 0 },
|
|
110
|
+
};
|
|
111
|
+
const json = await this.http.postForm("/note/folder", {
|
|
112
|
+
entry: JSON.stringify(entry),
|
|
113
|
+
});
|
|
114
|
+
if (json.result !== "ok" || !json.data?.entry) {
|
|
115
|
+
throw new Error(`创建文件夹失败: ${json.description ?? JSON.stringify(json)}`);
|
|
116
|
+
}
|
|
117
|
+
return json.data.entry;
|
|
118
|
+
}
|
|
119
|
+
/** 更新文件夹(如重命名) */
|
|
120
|
+
async updateFolder(folderId, folder) {
|
|
121
|
+
const json = await this.http.postForm(`/note/folder/${encodeURIComponent(folderId)}`, {
|
|
122
|
+
entry: JSON.stringify(folder),
|
|
123
|
+
});
|
|
124
|
+
if (json.result !== "ok") {
|
|
125
|
+
throw new Error(`更新文件夹失败: ${json.description ?? JSON.stringify(json)}`);
|
|
126
|
+
}
|
|
127
|
+
return json.data?.entry ?? folder;
|
|
128
|
+
}
|
|
129
|
+
/** 删除文件夹(默认移到回收站;purge=true 永久删除) */
|
|
130
|
+
async deleteFolder(folderId, tag, purge = false) {
|
|
131
|
+
await this.deleteEntity(folderId, tag, purge);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* 删除实体(笔记或文件夹共用同一端点)。
|
|
135
|
+
*
|
|
136
|
+
* 小米删除是两步状态机:`normal --(purge=false)--> deleted --(purge=true)--> 物理删除`,
|
|
137
|
+
* 不能跳步——对 normal 实体直接 purge 会返回「便签未被删除」(code 51006)。
|
|
138
|
+
* 因此 purge=true 时内部自动先软删除拿到新 tag,再用新 tag 永久删除。
|
|
139
|
+
* 每步删除都会让 tag 递增(乐观锁),故第二步必须用第一步返回的新 tag。
|
|
140
|
+
*/
|
|
141
|
+
async deleteEntity(id, tag, purge) {
|
|
142
|
+
// 第一步:软删除(移到回收站)
|
|
143
|
+
const soft = await this.postDelete(id, tag, false);
|
|
144
|
+
if (!purge)
|
|
145
|
+
return;
|
|
146
|
+
// 第二步:用软删除返回的新 tag 永久删除
|
|
147
|
+
const newTag = soft.data?.tag;
|
|
148
|
+
if (!newTag) {
|
|
149
|
+
throw new Error("软删除未返回新 tag,无法继续永久删除");
|
|
150
|
+
}
|
|
151
|
+
await this.postDelete(id, newTag, true);
|
|
152
|
+
}
|
|
153
|
+
/** 单次删除请求 */
|
|
154
|
+
async postDelete(id, tag, purge) {
|
|
155
|
+
const json = await this.http.postForm(`/note/full/${encodeURIComponent(id)}/delete`, {
|
|
156
|
+
tag,
|
|
157
|
+
purge: String(purge),
|
|
158
|
+
});
|
|
159
|
+
if (json.result !== "ok") {
|
|
160
|
+
throw new Error(`删除失败: ${json.description ?? JSON.stringify(json)}`);
|
|
161
|
+
}
|
|
162
|
+
if (json.data?.conflict) {
|
|
163
|
+
throw new Error("删除时发生冲突(tag 已过期),请重试");
|
|
164
|
+
}
|
|
165
|
+
return json;
|
|
166
|
+
}
|
|
167
|
+
// ============ 附件下载 ============
|
|
168
|
+
/** 下载附件文件到本地(已存在则跳过) */
|
|
169
|
+
async downloadFile(fileId, savePath) {
|
|
170
|
+
if (await fileExists(savePath))
|
|
171
|
+
return true;
|
|
172
|
+
const params = new URLSearchParams({
|
|
173
|
+
type: "note_img",
|
|
174
|
+
fileid: fileId,
|
|
175
|
+
ts: String(Date.now()),
|
|
176
|
+
});
|
|
177
|
+
const url = `${API_BASE}/file/full?${params}`;
|
|
178
|
+
const maxRetries = 2;
|
|
179
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
180
|
+
try {
|
|
181
|
+
const resp = await this.http.fetchRaw(url, { redirect: "follow" });
|
|
182
|
+
if (!resp.ok) {
|
|
183
|
+
if (attempt < maxRetries) {
|
|
184
|
+
await delay(500 * (attempt + 1));
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
const buffer = Buffer.from(await resp.arrayBuffer());
|
|
190
|
+
await ensureFileDir(savePath);
|
|
191
|
+
await writeFile(savePath, buffer);
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
if (err instanceof AuthExpiredError)
|
|
196
|
+
throw err;
|
|
197
|
+
if (attempt < maxRetries) {
|
|
198
|
+
await delay(500 * (attempt + 1));
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
// ============ 图片上传(两阶段 + 秒传) ============
|
|
207
|
+
/** 请求上传凭证 */
|
|
208
|
+
async requestUpload(meta) {
|
|
209
|
+
const payload = {
|
|
210
|
+
type: "note_img",
|
|
211
|
+
storage: {
|
|
212
|
+
filename: meta.filename,
|
|
213
|
+
size: meta.size,
|
|
214
|
+
sha1: meta.sha1,
|
|
215
|
+
mimeType: meta.mimeType,
|
|
216
|
+
kss: {
|
|
217
|
+
block_infos: [
|
|
218
|
+
{ blob: {}, size: meta.size, md5: meta.md5, sha1: meta.sha1 },
|
|
219
|
+
],
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
const json = await this.http.postForm("/file/v2/user/request_upload_file", { data: JSON.stringify(payload) });
|
|
224
|
+
if (json.result !== "ok" || !json.data) {
|
|
225
|
+
throw new Error(`请求上传凭证失败: ${json.description ?? JSON.stringify(json)}`);
|
|
226
|
+
}
|
|
227
|
+
return json;
|
|
228
|
+
}
|
|
229
|
+
/** 提交上传 */
|
|
230
|
+
async commitUpload(payload) {
|
|
231
|
+
const json = await this.http.postForm("/file/v2/user/commit", { commit: JSON.stringify(payload) });
|
|
232
|
+
if (json.result !== "ok" || !json.data?.fileId) {
|
|
233
|
+
throw new Error(`提交上传失败: ${json.description ?? JSON.stringify(json)}`);
|
|
234
|
+
}
|
|
235
|
+
return json;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* 上传图片,返回 { fileId, digest }。
|
|
239
|
+
* 流程:请求凭证 →(秒传则直接返回 fileId)→ 否则上传到 KSS 节点 → 提交。
|
|
240
|
+
*/
|
|
241
|
+
async uploadImage(buffer, params) {
|
|
242
|
+
const size = buffer.byteLength;
|
|
243
|
+
const sha1 = createHash("sha1").update(buffer).digest("hex");
|
|
244
|
+
const md5 = createHash("md5").update(buffer).digest("hex");
|
|
245
|
+
const tokenResp = await this.requestUpload({
|
|
246
|
+
filename: params.filename,
|
|
247
|
+
size,
|
|
248
|
+
sha1,
|
|
249
|
+
md5,
|
|
250
|
+
mimeType: params.mimeType,
|
|
251
|
+
});
|
|
252
|
+
// 秒传:服务端已有该文件,凭证响应直接含 fileId,无需上传与提交
|
|
253
|
+
if (tokenResp.data.fileId) {
|
|
254
|
+
return {
|
|
255
|
+
fileId: tokenResp.data.fileId,
|
|
256
|
+
digest: tokenResp.data.digest ?? "",
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const storage = tokenResp.data.storage;
|
|
260
|
+
if (!storage) {
|
|
261
|
+
throw new Error("上传凭证响应异常:既无 fileId 也无 storage");
|
|
262
|
+
}
|
|
263
|
+
const { uploadId, exists, kss } = storage;
|
|
264
|
+
let commitMetas = [];
|
|
265
|
+
if (!exists) {
|
|
266
|
+
const nodeUrl = kss.node_urls?.[0];
|
|
267
|
+
const blockMeta = kss.block_metas?.[0]?.block_meta;
|
|
268
|
+
if (!nodeUrl || !blockMeta) {
|
|
269
|
+
throw new Error("上传凭证缺少节点信息");
|
|
270
|
+
}
|
|
271
|
+
const uploadUrl = `${nodeUrl}/upload_block_chunk?chunk_pos=0&file_meta=${encodeURIComponent(kss.file_meta)}&block_meta=${encodeURIComponent(blockMeta)}`;
|
|
272
|
+
const uploadResp = await fetch(uploadUrl, {
|
|
273
|
+
method: "POST",
|
|
274
|
+
headers: { "Content-Type": "application/octet-stream" },
|
|
275
|
+
body: new Blob([buffer]),
|
|
276
|
+
});
|
|
277
|
+
if (!uploadResp.ok) {
|
|
278
|
+
const text = await uploadResp.text();
|
|
279
|
+
throw new Error(`上传图片数据失败 ${uploadResp.status}: ${text}`);
|
|
280
|
+
}
|
|
281
|
+
const metaBody = (await uploadResp.json());
|
|
282
|
+
if (!metaBody?.commit_meta) {
|
|
283
|
+
throw new Error("上传节点返回异常,缺少 commit_meta");
|
|
284
|
+
}
|
|
285
|
+
commitMetas = [{ commit_meta: metaBody.commit_meta }];
|
|
286
|
+
}
|
|
287
|
+
const commitPayload = {
|
|
288
|
+
storage: {
|
|
289
|
+
uploadId,
|
|
290
|
+
size,
|
|
291
|
+
sha1,
|
|
292
|
+
kss: { file_meta: kss.file_meta, commit_metas: commitMetas },
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
const committed = await this.commitUpload(commitPayload);
|
|
296
|
+
return { fileId: committed.data.fileId, digest: committed.data.digest };
|
|
297
|
+
}
|
|
298
|
+
}
|