@orielweb/api 0.0.0-stage → 0.4.15
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 +21 -0
- package/README.md +175 -2
- package/package.json +117 -4
- package/src/app.js +347 -0
- package/src/autostart.js +47 -0
- package/src/clipboard.js +185 -0
- package/src/core.js +288 -0
- package/src/dialog.js +193 -0
- package/src/dpi.js +392 -0
- package/src/event.js +471 -0
- package/src/fs.js +863 -0
- package/src/globals.d.ts +22 -0
- package/src/image-bytes.js +147 -0
- package/src/image.js +407 -0
- package/src/internal.js +81 -0
- package/src/menu.js +1216 -0
- package/src/mocks.js +185 -0
- package/src/notification.js +461 -0
- package/src/opener.js +74 -0
- package/src/path.js +335 -0
- package/src/tray.js +451 -0
- package/src/types.d.ts +61 -0
- package/src/webviewWindow.js +221 -0
- package/src/window.js +2169 -0
- package/types/app.d.ts +231 -0
- package/types/autostart.d.ts +25 -0
- package/types/clipboard.d.ts +103 -0
- package/types/core.d.ts +153 -0
- package/types/dialog.d.ts +89 -0
- package/types/dpi.d.ts +231 -0
- package/types/event.d.ts +132 -0
- package/types/fs.d.ts +502 -0
- package/types/image-bytes.d.ts +49 -0
- package/types/image.d.ts +165 -0
- package/types/internal.d.ts +24 -0
- package/types/menu.d.ts +627 -0
- package/types/mocks.d.ts +60 -0
- package/types/notification.d.ts +267 -0
- package/types/opener.d.ts +37 -0
- package/types/path.d.ts +239 -0
- package/types/tray.d.ts +180 -0
- package/types/types.d.ts +61 -0
- package/types/webviewWindow.d.ts +112 -0
- package/types/window.d.ts +1139 -0
package/src/fs.js
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// 对标 `@tauri-apps/plugin-fs`:整文件族 + 句柄族(B17 起)。
|
|
2
|
+
//
|
|
3
|
+
// 本模块每个函数都要过**两道关**:宿主侧的命令授权(`Allow("fs.readTextFile")`)
|
|
4
|
+
// 与**路径 scope**(`Allow("fs.readTextFile", s => s.AllowPath("$APPDATA/**"))`)。
|
|
5
|
+
// 少了后者,一条 XSS 就能把 ~/.ssh/id_rsa 读走——所以本模块与 `path` 有本质差别:
|
|
6
|
+
// `path` 只做运算不碰文件系统,整族无需声明;`fs` 碰文件系统,**必须逐条声明 scope**。
|
|
7
|
+
//
|
|
8
|
+
// 与 Tauri 的差别(如实标注,不假装一致):
|
|
9
|
+
//
|
|
10
|
+
// * **句柄族是 B17 新增的**:`open` / `create` / `FileHandle` / `SeekMode` 已提供,
|
|
11
|
+
// 宿主侧有一张 id 句柄表(对标 Tauri 的资源表,见 OrielFileHandleRegistry)。
|
|
12
|
+
// **scope 只在 open/create 时判**——拿到句柄后的读写不再看路径(与 Tauri 相同)。
|
|
13
|
+
// 句柄的参数面(read/write/seek/fstat/ftruncate/close)是三平台一致的文件 I/O,
|
|
14
|
+
// 没有平台落点差异。
|
|
15
|
+
// * **`readTextFileLines` 不流式**:返回的是一个 async 迭代器,但宿主侧是
|
|
16
|
+
// "整文件读入 → 切行"(本库 IPC 是纯 JSON,真流式要占一条 Channel)。
|
|
17
|
+
// 迭代契约与 Tauri 一致,代价是内存 = 文件大小;大文件请用 `open` + 分块 `read`。
|
|
18
|
+
// * **二进制走 JSON 数字数组**:`readFile` 给 `Uint8Array`、`writeFile` 收 `Uint8Array`,
|
|
19
|
+
// 但通道是 JSON,所以一个字节要变成两三个字符。几十 MB 级别的文件不适用。
|
|
20
|
+
// Tauri 用 `invoke` 的二进制 body 传,本库的 IPC 是纯 JSON,没有那条路。
|
|
21
|
+
// `FileHandle.read` 的块大小因此有上限(8 MiB/次),见该方法的说明。
|
|
22
|
+
// * **`lstat` 与 `stat` 的差别只在"链接自身算不算"**:.NET 对符号链接会跟随,
|
|
23
|
+
// 所以两者返回的元数据相同、只是 `isSymlink` 如实报告。
|
|
24
|
+
// * **监视自 B20 起提供**(`watch` / `watchImmediate`):底层是 .NET 的
|
|
25
|
+
// `FileSystemWatcher`,与 Tauri 的 `notify` 落到**同一组系统设施**上
|
|
26
|
+
// (ReadDirectoryChangesW / inotify / FSEvents),所以"能看到哪些变化"基本一致。
|
|
27
|
+
// 差别在归类与 debounce 的合并算法(见 `WatchEvent` 与 `watch` 的说明),
|
|
28
|
+
// 以及**事件只回给发起监视的那个窗口**(Tauri 的 Channel 也绑在调用方 webview 上)。
|
|
29
|
+
|
|
30
|
+
import { invoke } from './core.js';
|
|
31
|
+
import { getTransport } from './internal.js';
|
|
32
|
+
import * as paths from './path.js';
|
|
33
|
+
|
|
34
|
+
// `BaseDirectory` 从 path 模块 re-export(Tauri 的 plugin-fs 也这么干):
|
|
35
|
+
// 迁移代码 `import { BaseDirectory } from '@tauri-apps/plugin-fs'` 能直接改前缀。
|
|
36
|
+
export { BaseDirectory } from './path.js';
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* `BaseDirectory` 枚举值 → `path` 模块的目录函数名(键值与 Tauri 的同名枚举逐键一致)。
|
|
40
|
+
*
|
|
41
|
+
* @type {Record<number, string>}
|
|
42
|
+
*/
|
|
43
|
+
const BASE_DIR_GETTERS = {
|
|
44
|
+
1: 'audioDir', 2: 'cacheDir', 3: 'configDir', 4: 'dataDir', 5: 'localDataDir',
|
|
45
|
+
6: 'documentDir', 7: 'downloadDir', 8: 'pictureDir', 9: 'publicDir', 10: 'videoDir',
|
|
46
|
+
11: 'resourceDir', 12: 'tempDir', 13: 'appConfigDir', 14: 'appDataDir',
|
|
47
|
+
15: 'appLocalDataDir', 16: 'appCacheDir', 17: 'appLogDir', 18: 'desktopDir',
|
|
48
|
+
19: 'executableDir', 20: 'fontDir', 21: 'homeDir', 22: 'runtimeDir', 23: 'templateDir',
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** 粗判"已经是绝对路径"(`/`、`X:\`、`\\`)——绝对路径不参与 baseDir 解析(Tauri 语义)。 */
|
|
52
|
+
/** @param {unknown} path */
|
|
53
|
+
function looksAbsolute(path) {
|
|
54
|
+
return typeof path === 'string'
|
|
55
|
+
&& (path.startsWith('/') || path.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(path));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 把相对路径按 `options.baseDir` 解析成绝对路径(B13 与 Tauri 的 `baseDir` 语义对齐)。
|
|
60
|
+
*
|
|
61
|
+
* @param {string} fnName
|
|
62
|
+
* @param {unknown} path
|
|
63
|
+
* @param {Record<string, unknown> | null | undefined} options
|
|
64
|
+
* @returns {Promise<unknown>} 没有 baseDir 时原样返回;有则返回解析后的字符串。
|
|
65
|
+
*/
|
|
66
|
+
async function resolveAgainstBase(fnName, path, options) {
|
|
67
|
+
const baseDir = options?.baseDir;
|
|
68
|
+
if (baseDir === undefined || baseDir === null) {
|
|
69
|
+
return path;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (typeof path !== 'string') {
|
|
73
|
+
return path;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (looksAbsolute(path)) {
|
|
77
|
+
return path;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const getterName = BASE_DIR_GETTERS[/** @type {number} */ (baseDir)];
|
|
81
|
+
if (getterName === undefined) {
|
|
82
|
+
return Promise.reject(new Error(
|
|
83
|
+
`${fnName}: 不认识的 baseDir 值 ${JSON.stringify(baseDir)}。` +
|
|
84
|
+
`请用 '@orielweb/api/path' 的 BaseDirectory 枚举(与 Tauri 同值)。`));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const getters = /** @type {Record<string, () => Promise<string>>} */ (/** @type {unknown} */ (paths));
|
|
88
|
+
const getter = getters[getterName];
|
|
89
|
+
if (getter === undefined) {
|
|
90
|
+
return Promise.reject(new Error(`${fnName}: 目录函数 ${getterName} 不存在(BaseDirectory 值与库版本不匹配)。`));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const dir = await getter();
|
|
94
|
+
return `${dir}/${path}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 校验 Tauri 签名里的 `options` 位置。
|
|
99
|
+
*
|
|
100
|
+
* @param {string} fnName 调用方函数名(报错里要能定位到是哪个函数)
|
|
101
|
+
* @param {unknown} options 调用方传进来的 options
|
|
102
|
+
* @param {string[]} allowedKeys 本库**真正支持**的键(`baseDir` 恒被接受,不必列入)
|
|
103
|
+
* @returns {Error | null} 有问题时返回错误对象,由调用方 reject
|
|
104
|
+
* @remarks
|
|
105
|
+
* `baseDir` 自 B13 起**受支持**(此前拒绝):语义与 Tauri 一致——相对路径按
|
|
106
|
+
* `BaseDirectory` 枚举解析到对应目录,绝对路径不参与。解析在页面侧完成
|
|
107
|
+
* (`path` 的目录函数 + 拼接),宿主收到的始终是绝对路径。
|
|
108
|
+
*/
|
|
109
|
+
function checkOptions(fnName, options, allowedKeys) {
|
|
110
|
+
if (options === undefined || options === null) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (typeof options !== 'object' || Array.isArray(options)) {
|
|
115
|
+
return new TypeError(`${fnName}: options 必须是对象,收到 ${Array.isArray(options) ? 'array' : typeof options}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// 到这里已经确认是对象;`unknown` 上读不到属性,所以显式收窄一次。
|
|
119
|
+
const opts = /** @type {Record<string, unknown>} */ (options);
|
|
120
|
+
|
|
121
|
+
const unknown = Object.keys(opts).filter((key) => key !== 'baseDir' && !allowedKeys.includes(key));
|
|
122
|
+
if (unknown.length > 0) {
|
|
123
|
+
return new Error(
|
|
124
|
+
`${fnName}: 不支持的选项 ${unknown.map((k) => `\`${k}\``).join(', ')}。` +
|
|
125
|
+
`本库该函数只接受 ${(allowedKeys.length > 0 ? allowedKeys : ['baseDir']).map((k) => `\`${k}\``).join('/')}。`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 带 options 校验与 baseDir 解析的 `invoke`。
|
|
133
|
+
*
|
|
134
|
+
* @param {string} fnName
|
|
135
|
+
* @param {string} command
|
|
136
|
+
* @param {Record<string, unknown>} args
|
|
137
|
+
* @param {unknown} options
|
|
138
|
+
* @param {string[]} [allowedKeys]
|
|
139
|
+
* @param {string[]} [pathKeys] 参数里**要按 baseDir 解析**的键(默认 `['path']`)
|
|
140
|
+
* @returns {Promise<any>}
|
|
141
|
+
*/
|
|
142
|
+
async function invokeWithOptions(fnName, command, args, options, allowedKeys = [], pathKeys = ['path']) {
|
|
143
|
+
const problem = checkOptions(fnName, options, allowedKeys);
|
|
144
|
+
if (problem !== null) {
|
|
145
|
+
return Promise.reject(problem);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const opts = /** @type {Record<string, unknown> | null | undefined} */ (options);
|
|
149
|
+
const resolved = { ...args };
|
|
150
|
+
for (const key of pathKeys) {
|
|
151
|
+
resolved[key] = await resolveAgainstBase(fnName, resolved[key], opts);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return invoke(command, resolved);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 读文本文件(UTF-8)。
|
|
159
|
+
*
|
|
160
|
+
* @param {string} path 绝对路径,或相对进程当前目录的路径。
|
|
161
|
+
* @param {{ baseDir?: number }} [options] `baseDir` 用 `BaseDirectory` 枚举把相对路径解析到对应目录(绝对路径不参与)
|
|
162
|
+
* @returns {Promise<string>}
|
|
163
|
+
*/
|
|
164
|
+
export function readTextFile(path, options) {
|
|
165
|
+
return invokeWithOptions('readTextFile', 'fs.readTextFile', { path }, options);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 写文本文件(UTF-8)。
|
|
170
|
+
*
|
|
171
|
+
* @param {string} path
|
|
172
|
+
* @param {string} data
|
|
173
|
+
* @param {{ baseDir?: number }} [options]
|
|
174
|
+
* @returns {Promise<void>}
|
|
175
|
+
* @remarks **父目录会自动创建**:不自动建的话每次写都要先 `mkdir`,
|
|
176
|
+
* 而漏建的症状是 `DirectoryNotFoundException`——报错说"目录不存在",调用方以为在写文件。
|
|
177
|
+
*/
|
|
178
|
+
export function writeTextFile(path, data, options) {
|
|
179
|
+
return invokeWithOptions('writeTextFile', 'fs.writeTextFile', { path, data }, options);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 读二进制文件。
|
|
184
|
+
*
|
|
185
|
+
* @param {string} path
|
|
186
|
+
* @param {{ baseDir?: number }} [options]
|
|
187
|
+
* @returns {Promise<Uint8Array>}
|
|
188
|
+
*/
|
|
189
|
+
export async function readFile(path, options) {
|
|
190
|
+
const bytes = await invokeWithOptions('readFile', 'fs.readFile', { path }, options);
|
|
191
|
+
return new Uint8Array(bytes);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* 写二进制文件。
|
|
196
|
+
*
|
|
197
|
+
* @param {string} path
|
|
198
|
+
* @param {Uint8Array | number[]} data
|
|
199
|
+
* @param {{ baseDir?: number }} [options]
|
|
200
|
+
* @returns {Promise<void>}
|
|
201
|
+
* @remarks
|
|
202
|
+
* 传 `Uint8Array` 时这里会转成普通数组再发:JSON 不认 `Uint8Array`,
|
|
203
|
+
* 直接塞进 `JSON.stringify` 会得到一个**对象**(`{"0":1,"1":2}`)而不是数组,
|
|
204
|
+
* 而宿主侧期望数组、会报类型不符。
|
|
205
|
+
*/
|
|
206
|
+
export function writeFile(path, data, options) {
|
|
207
|
+
return invokeWithOptions('writeFile', 'fs.writeFile', { path, data: Array.from(data) }, options);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 路径是否存在。
|
|
212
|
+
*
|
|
213
|
+
* @param {string} path
|
|
214
|
+
* @param {{ baseDir?: number }} [options]
|
|
215
|
+
* @returns {Promise<boolean>}
|
|
216
|
+
* @remarks **也要过 scope**:不过的话它就成了一个"这台机器上有哪些文件"的探测器,
|
|
217
|
+
* 而那种信息在攻防里很有用(先枚举、再决定读什么)。
|
|
218
|
+
*/
|
|
219
|
+
export function exists(path, options) {
|
|
220
|
+
return invokeWithOptions('exists', 'fs.exists', { path }, options);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* 文件大小(字节)。目录返回宿主定义的值(通常 0)。
|
|
225
|
+
*
|
|
226
|
+
* @param {string} path
|
|
227
|
+
* @param {{ baseDir?: number }} [options]
|
|
228
|
+
* @returns {Promise<number>}
|
|
229
|
+
*/
|
|
230
|
+
export function size(path, options) {
|
|
231
|
+
return invokeWithOptions('size', 'fs.size', { path }, options);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* 目录项列表。
|
|
236
|
+
*
|
|
237
|
+
* @param {string} path
|
|
238
|
+
* @param {{ baseDir?: number }} [options]
|
|
239
|
+
* @returns {Promise<Array<{ name: string, isFile: boolean, isDirectory: boolean, isSymlink: boolean }>>}
|
|
240
|
+
*/
|
|
241
|
+
export function readDir(path, options) {
|
|
242
|
+
return invokeWithOptions('readDir', 'fs.readDir', { path }, options);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 文件元信息(跟随符号链接)。
|
|
247
|
+
*
|
|
248
|
+
* @param {string} path
|
|
249
|
+
* @param {{ baseDir?: number }} [options]
|
|
250
|
+
* @returns {Promise<{ isFile: boolean, isDirectory: boolean, isSymlink: boolean,
|
|
251
|
+
* size: number, mtime: number, atime: number, birthtime: number }>}
|
|
252
|
+
* @remarks 时间是**毫秒时间戳**(Unix epoch,UTC),不是 `Date`。
|
|
253
|
+
* 与 Tauri 的差别:那边给 `Date` 对象。用时间戳是因为它跨 JSON 无损,
|
|
254
|
+
* 而 `Date` 要走 `new Date(x)` 转换——构造一杯都行,但时间戳更少一层意外。
|
|
255
|
+
*/
|
|
256
|
+
export function stat(path, options) {
|
|
257
|
+
return invokeWithOptions('stat', 'fs.stat', { path }, options);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* 文件元信息(**不跟随**符号链接)。
|
|
262
|
+
*
|
|
263
|
+
* @param {string} path
|
|
264
|
+
* @param {{ baseDir?: number }} [options]
|
|
265
|
+
* @returns {Promise<object>}
|
|
266
|
+
* @remarks 当前与 {@link stat} 返回同样的元数据(只是 `isSymlink` 如实报告)。
|
|
267
|
+
* .NET 跟随符号链接,编出链接自身的长度/时间要额外做系统调用,本库目前不需要那个精度。
|
|
268
|
+
*/
|
|
269
|
+
export function lstat(path, options) {
|
|
270
|
+
return invokeWithOptions('lstat', 'fs.lstat', { path }, options);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 创建目录。
|
|
275
|
+
*
|
|
276
|
+
* @param {string} path
|
|
277
|
+
* @param {{ recursive?: boolean, baseDir?: number }} [options]
|
|
278
|
+
* @returns {Promise<void>}
|
|
279
|
+
* @remarks 非递归且目录已存在 → 报错(与 Tauri / Node 一致);递归时已存在是正常的。
|
|
280
|
+
*/
|
|
281
|
+
export function mkdir(path, options) {
|
|
282
|
+
return invokeWithOptions(
|
|
283
|
+
'mkdir', 'fs.mkdir',
|
|
284
|
+
options?.recursive === true ? { path, recursive: true } : { path },
|
|
285
|
+
options, ['recursive']);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* 删除文件或目录。
|
|
290
|
+
*
|
|
291
|
+
* @param {string} path
|
|
292
|
+
* @param {{ recursive?: boolean, baseDir?: number }} [options] 删目录时必须为 `true`(否则非空目录会报错)。
|
|
293
|
+
* @returns {Promise<void>}
|
|
294
|
+
*/
|
|
295
|
+
export function remove(path, options) {
|
|
296
|
+
return invokeWithOptions(
|
|
297
|
+
'remove', 'fs.remove',
|
|
298
|
+
options?.recursive === true ? { path, recursive: true } : { path },
|
|
299
|
+
options, ['recursive']);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 重命名 / 移动。
|
|
304
|
+
*
|
|
305
|
+
* @param {string} oldPath
|
|
306
|
+
* @param {string} newPath
|
|
307
|
+
* @param {{ baseDir?: number }} [options]
|
|
308
|
+
* @returns {Promise<void>}
|
|
309
|
+
* @remarks **两个路径都要在 scope 内**:只查源的话,页面能把允许目录里的文件
|
|
310
|
+
* "搬"到 scope 之外(那是一次写)。
|
|
311
|
+
*/
|
|
312
|
+
export function rename(oldPath, newPath, options) {
|
|
313
|
+
return invokeWithOptions('rename', 'fs.rename', { oldPath, newPath }, options, [], ['oldPath', 'newPath']);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* 复制文件。
|
|
318
|
+
*
|
|
319
|
+
* @param {string} fromPath
|
|
320
|
+
* @param {string} toPath
|
|
321
|
+
* @param {{ baseDir?: number }} [options]
|
|
322
|
+
* @returns {Promise<void>}
|
|
323
|
+
* @remarks 同 {@link rename}:两个路径都要过 scope。目标已存在时**覆盖**。
|
|
324
|
+
*/
|
|
325
|
+
export function copyFile(fromPath, toPath, options) {
|
|
326
|
+
return invokeWithOptions('copyFile', 'fs.copyFile', { oldPath: fromPath, newPath: toPath }, options, [], ['oldPath', 'newPath']);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 截断(或扩展)文件到指定长度。
|
|
331
|
+
*
|
|
332
|
+
* @param {string} path
|
|
333
|
+
* @param {number} [len] 目标长度(字节);大于当前长度时用零填充。省略时宿主按 0 处理。
|
|
334
|
+
* @param {{ baseDir?: number }} [options] **第 3 参**:第 2 参是 `len`,不是 options
|
|
335
|
+
* @returns {Promise<void>}
|
|
336
|
+
*/
|
|
337
|
+
export function truncate(path, len, options) {
|
|
338
|
+
// 注意参数位置:Tauri 的签名是 `truncate(path, len?, options?)`。
|
|
339
|
+
// 若照"第二个参数就是 options"的印象写校验,会把长度当选项拒掉。
|
|
340
|
+
return invokeWithOptions('truncate', 'fs.truncate', { path, len }, options);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
// 句柄族(B17,对标 Tauri 的 open / create / FileHandle / SeekMode)
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
//
|
|
347
|
+
// 宿主侧有一张 **id 句柄表**(应用级,对标 Tauri 的资源表)。
|
|
348
|
+
// **scope 只在 open / create 时判**:拿到句柄后的读写不再看路径——句柄代表
|
|
349
|
+
// "已经过授权的那个打开的文件",反复按路径重判既无意义(路径可能已经变了),
|
|
350
|
+
// 也会把"同一文件换了名字就打不开"变成常态。这与 Tauri 一致。
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 定位方式(对标 Tauri 的 `SeekMode`)。
|
|
354
|
+
*
|
|
355
|
+
* @readonly
|
|
356
|
+
* @remarks 取值与 Tauri 的 TS 枚举逐键一致(`Start` = 0 / `Current` = 1 / `End` = 2)。
|
|
357
|
+
* 反向映射(`0: 'Start'` 这类)也一并给:Tauri 的数值枚举在运行期就有它们,
|
|
358
|
+
* 迁移代码里两种写法都可能出现(与 `BaseDirectory` 同一理由)。
|
|
359
|
+
*/
|
|
360
|
+
export const SeekMode = Object.freeze({
|
|
361
|
+
Start: 0,
|
|
362
|
+
Current: 1,
|
|
363
|
+
End: 2,
|
|
364
|
+
// 反向映射
|
|
365
|
+
0: 'Start',
|
|
366
|
+
1: 'Current',
|
|
367
|
+
2: 'End',
|
|
368
|
+
});
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* 一个打开的文件句柄(对标 Tauri 的 `FileHandle`)。
|
|
372
|
+
*
|
|
373
|
+
* @remarks
|
|
374
|
+
* 用 {@link open} / {@link create} 取得。**用完要 `close()`**——句柄占着操作系统的
|
|
375
|
+
* 文件描述符,应用退出时会由宿主统一关闭(`OrielApp.Dispose` 里的句柄表清理),
|
|
376
|
+
* 但长跑的应用自己关才是正确的做法。
|
|
377
|
+
*
|
|
378
|
+
* 本类没有 `disk` 之类的属性;`rid` 是**补壳**(返回句柄 id)——Tauri 那边它是
|
|
379
|
+
* 资源表里的编号,本库没有通用资源表,id 就是句柄号,语义上正好对得上。
|
|
380
|
+
*/
|
|
381
|
+
export class FileHandle {
|
|
382
|
+
/**
|
|
383
|
+
* @param {number} id 宿主分配的句柄 id(内部用;页面侧从 open/create 得到实例)。
|
|
384
|
+
*/
|
|
385
|
+
constructor(id) {
|
|
386
|
+
/** @type {number} */
|
|
387
|
+
this.id = id;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* 句柄编号(对标 `Resource.rid`)。
|
|
392
|
+
*
|
|
393
|
+
* @returns {number}
|
|
394
|
+
*/
|
|
395
|
+
get rid() {
|
|
396
|
+
return this.id;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 从当前读写位置读一段字节,**填进传入的缓冲区**(与 Tauri 一致)。
|
|
401
|
+
*
|
|
402
|
+
* @param {Uint8Array} buffer 要填的缓冲区;读多少由它的长度决定。
|
|
403
|
+
* @returns {Promise<number | null>} 实际读到的字节数;**已到文件末尾返回 `null`**。
|
|
404
|
+
* @remarks
|
|
405
|
+
* 返回 `null`(而不是 0)是为了与"读到了 0 字节"区分开——Tauri 同样是
|
|
406
|
+
* `number | null`。单次最多 8 MiB(本库 IPC 是纯 JSON,一次读一大块没有意义;
|
|
407
|
+
* 需要更大范围请分块循环)。
|
|
408
|
+
*
|
|
409
|
+
* 缓冲区长度为 0 时直接返回 0,不发 IPC。
|
|
410
|
+
*/
|
|
411
|
+
async read(buffer) {
|
|
412
|
+
if (!(buffer instanceof Uint8Array)) {
|
|
413
|
+
throw new TypeError('FileHandle.read: 需要 Uint8Array 作为缓冲区。');
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
if (buffer.length === 0) {
|
|
417
|
+
return 0;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** @type {number[] | null} */
|
|
421
|
+
const bytes = await invoke('fs.read', { id: this.id, length: buffer.length });
|
|
422
|
+
if (bytes === null || bytes === undefined) {
|
|
423
|
+
return null;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
const chunk = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes);
|
|
427
|
+
buffer.set(chunk, 0);
|
|
428
|
+
return chunk.length;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* 从当前读写位置写入一段字节。
|
|
433
|
+
*
|
|
434
|
+
* @param {Uint8Array | number[]} data
|
|
435
|
+
* @returns {Promise<number>} 写入的字节数。
|
|
436
|
+
* @remarks
|
|
437
|
+
* **不逐次落盘**:缓冲交给操作系统(Tauri 的 `write_all` 同样不 flush)。
|
|
438
|
+
* 同一个句柄里的 write → seek → read 是缓冲一致的;要确保别的进程/句柄
|
|
439
|
+
* 立刻看到内容,请 `close()`(关闭时会落盘)。
|
|
440
|
+
*/
|
|
441
|
+
async write(data) {
|
|
442
|
+
/** @type {number[] | null} */
|
|
443
|
+
const bytes = data instanceof Uint8Array ? Array.from(data)
|
|
444
|
+
: Array.isArray(data) ? data
|
|
445
|
+
: null;
|
|
446
|
+
if (bytes === null) {
|
|
447
|
+
throw new TypeError('FileHandle.write: data 必须是 Uint8Array 或 number[]。');
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
return invoke('fs.write', { id: this.id, data: bytes });
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 移动读写位置。
|
|
455
|
+
*
|
|
456
|
+
* @param {number} offset 偏移量(字节,可为负——负值从 End/Current 往回退)。
|
|
457
|
+
* @param {number} [whence] 定位方式,见 {@link SeekMode};缺省 `SeekMode.Start`。
|
|
458
|
+
* @returns {Promise<number>} 新的绝对位置(从文件头算)。
|
|
459
|
+
* @remarks 移到文件头之前是错误(宿主会抛,而不是静默钳到 0)。
|
|
460
|
+
*/
|
|
461
|
+
async seek(offset, whence = SeekMode.Start) {
|
|
462
|
+
if (typeof offset !== 'number' || !Number.isFinite(offset)) {
|
|
463
|
+
throw new TypeError('FileHandle.seek: offset 必须是有限数字。');
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return invoke('fs.seek', { id: this.id, offset, whence });
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* 这个打开文件的元信息(形状与 {@link stat} 一致)。
|
|
471
|
+
*
|
|
472
|
+
* @returns {Promise<{ isFile: boolean, isDirectory: boolean, isSymlink: boolean,
|
|
473
|
+
* size: number, mtime: number, atime: number, birthtime: number }>}
|
|
474
|
+
* @remarks 取的是**描述符**上的元信息:文件被改名/挪走之后仍然给得出正确值
|
|
475
|
+
* (`fs.stat` 按路径查,那种场景会报"找不到文件")。
|
|
476
|
+
* `isSymlink` 恒为 `false`——句柄已经跟随过链接,与 Rust 的 `File::metadata()` 一致。
|
|
477
|
+
* `size` 是句柄看到的**当前**长度。
|
|
478
|
+
*/
|
|
479
|
+
stat() {
|
|
480
|
+
return invoke('fs.fstat', { id: this.id });
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* 把文件截断(或扩展到)指定长度。
|
|
485
|
+
*
|
|
486
|
+
* @param {number} [len] 目标长度;**省略时截到当前读写位置**(与 Tauri 一致)。
|
|
487
|
+
* @returns {Promise<void>}
|
|
488
|
+
*/
|
|
489
|
+
async truncate(len) {
|
|
490
|
+
/** @type {Record<string, unknown>} */
|
|
491
|
+
const args = { id: this.id };
|
|
492
|
+
if (len !== undefined) {
|
|
493
|
+
args.len = len;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
await invoke('fs.ftruncate', args);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 关闭句柄(触发落盘并释放文件描述符)。
|
|
501
|
+
*
|
|
502
|
+
* @returns {Promise<void>}
|
|
503
|
+
* @remarks **不可重复关闭**:第二次 `close()` 会报"句柄不存在或已关闭"
|
|
504
|
+
* (与 Tauri 的 Resource 语义一致)。关闭后的读写同样报这个错。
|
|
505
|
+
*/
|
|
506
|
+
async close() {
|
|
507
|
+
await invoke('fs.close', { id: this.id });
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* 打开一个已存在的文件(或按选项创建),拿到句柄(对标 Tauri 的 `open`)。
|
|
513
|
+
*
|
|
514
|
+
* @param {string} path
|
|
515
|
+
* @param {{ read?: boolean, write?: boolean, append?: boolean, truncate?: boolean,
|
|
516
|
+
* create?: boolean, createNew?: boolean, baseDir?: number }} [options]
|
|
517
|
+
* @returns {Promise<FileHandle>}
|
|
518
|
+
* @remarks
|
|
519
|
+
* 选项语义与 Tauri(Rust 的 `OpenOptions`)一致:
|
|
520
|
+
* `read` / `write` / `append` **至少要有一个为 `true`**(全 false 打开没有意义,宿主会报错);
|
|
521
|
+
* `truncate` 需要写权限;`createNew`(必须不存在)与 `create`(允许已存在)互斥。
|
|
522
|
+
* 冲突组合**当场报错**而不是猜一个意图——猜错会截断数据或意外建文件。
|
|
523
|
+
*
|
|
524
|
+
* 需要能力声明(`fs.open`)与**路径 scope**。
|
|
525
|
+
*/
|
|
526
|
+
export async function open(path, options) {
|
|
527
|
+
const flags = ['read', 'write', 'append', 'truncate', 'create', 'createNew'];
|
|
528
|
+
const problem = checkOptions('open', options, flags);
|
|
529
|
+
if (problem !== null) {
|
|
530
|
+
throw problem;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const opts = /** @type {Record<string, unknown> | null | undefined} */ (options);
|
|
534
|
+
/** @type {Record<string, unknown>} */
|
|
535
|
+
const args = { path };
|
|
536
|
+
for (const key of flags) {
|
|
537
|
+
const value = opts?.[key];
|
|
538
|
+
if (value !== undefined) {
|
|
539
|
+
args[key] = value;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
args.path = await resolveAgainstBase('open', path, opts);
|
|
544
|
+
|
|
545
|
+
const id = await invoke('fs.open', args);
|
|
546
|
+
return new FileHandle(id);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* 创建一个文件(已存在则清空)并打开句柄(对标 Tauri 的 `create`)。
|
|
551
|
+
*
|
|
552
|
+
* @param {string} path
|
|
553
|
+
* @param {{ baseDir?: number }} [options]
|
|
554
|
+
* @returns {Promise<FileHandle>}
|
|
555
|
+
* @remarks 等价于 `open(path, { write: true, create: true, truncate: true, read: true })`。
|
|
556
|
+
* **父目录会自动创建**——与本库 `writeTextFile` 的既有约定一致。
|
|
557
|
+
*
|
|
558
|
+
* 需要能力声明(`fs.create`)与**路径 scope**。
|
|
559
|
+
*/
|
|
560
|
+
export async function create(path, options) {
|
|
561
|
+
const id = await invokeWithOptions('create', 'fs.create', { path }, options);
|
|
562
|
+
return new FileHandle(id);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* 逐行读一个文本文件(UTF-8),返回异步迭代器(对标 Tauri 的 `readTextFileLines`)。
|
|
567
|
+
*
|
|
568
|
+
* @param {string} path
|
|
569
|
+
* @param {{ baseDir?: number }} [options]
|
|
570
|
+
* @returns {Promise<AsyncIterableIterator<string>>}
|
|
571
|
+
* @remarks
|
|
572
|
+
* ```js
|
|
573
|
+
* for await (const line of await readTextFileLines('app.log')) {
|
|
574
|
+
* console.log(line);
|
|
575
|
+
* }
|
|
576
|
+
* ```
|
|
577
|
+
* **迭代契约与 Tauri 一致,但不是流式**:宿主侧整文件读入再切行(本库的 IPC
|
|
578
|
+
* 是纯 JSON,真流式要占一条 Channel)。代价是内存 = 文件大小——大文件请用
|
|
579
|
+
* {@link open} + 分块 {@link FileHandle.read} 自己处理。
|
|
580
|
+
*
|
|
581
|
+
* 切分规则:按 `\n` 切、去掉紧随的 `\r`(CRLF/LF 都支持);末尾换行不产生空行,
|
|
582
|
+
* 文件中间的空行照常保留。空文件给零行。
|
|
583
|
+
*
|
|
584
|
+
* 需要能力声明(`fs.readTextFileLines`)与**路径 scope**。
|
|
585
|
+
*/
|
|
586
|
+
export async function readTextFileLines(path, options) {
|
|
587
|
+
/** @type {string[]} */
|
|
588
|
+
const lines = await invokeWithOptions('readTextFileLines', 'fs.readTextFileLines', { path }, options);
|
|
589
|
+
|
|
590
|
+
return (async function* () {
|
|
591
|
+
for (const line of lines) {
|
|
592
|
+
yield line;
|
|
593
|
+
}
|
|
594
|
+
})();
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
// ---------------------------------------------------------------------------
|
|
599
|
+
// 监视族(B20,对标 Tauri 的 watch / watchImmediate,需要 Rust 侧的 watch feature)
|
|
600
|
+
// ---------------------------------------------------------------------------
|
|
601
|
+
//
|
|
602
|
+
// 宿主侧每个监视器占一个编号(应用级登记表,见 OrielFsWatcherRegistry);
|
|
603
|
+
// 事件经 `oriel://fs-watch/<id>` 只回给**发起监视的那个窗口**。
|
|
604
|
+
//
|
|
605
|
+
// 与 Tauri 的两处差别,都如实写在下面的注释与 docs/API.md 里:
|
|
606
|
+
// 1. 事件种类的归类有三处降级(`FileSystemWatcher` 给不出更细的信息);
|
|
607
|
+
// 2. debounce 是"按路径合并、后来的种类覆盖先前的",不是 notify-debouncer-full
|
|
608
|
+
// 的逐字段合并算法。
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* 一次变化里"访问"的种类(对标 Tauri 的 `WatchEventKindAccess`)。
|
|
612
|
+
*
|
|
613
|
+
* @typedef {{ kind: 'any' }
|
|
614
|
+
* | { kind: 'close', mode: WatchEventMode }
|
|
615
|
+
* | { kind: 'open', mode: WatchEventMode }
|
|
616
|
+
* | { kind: 'other' }} WatchEventKindAccess
|
|
617
|
+
*/
|
|
618
|
+
|
|
619
|
+
/**
|
|
620
|
+
* 访问模式(对标 Tauri 的 `WatchEventKindClose`/`Open` 的 `mode`)。
|
|
621
|
+
*
|
|
622
|
+
* @typedef {'any' | 'execute' | 'read' | 'write' | 'other'} WatchEventMode
|
|
623
|
+
*/
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* 新建了什么(对标 Tauri 的 `WatchEventKindCreate`)。
|
|
627
|
+
*
|
|
628
|
+
* @typedef {{ kind: 'any' } | { kind: 'file' } | { kind: 'folder' } | { kind: 'other' }} WatchEventKindCreate
|
|
629
|
+
*/
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* 改了什么(对标 Tauri 的 `WatchEventKindModify`)。
|
|
633
|
+
*
|
|
634
|
+
* @typedef {{ kind: 'any' }
|
|
635
|
+
* | { kind: 'data', mode: 'any' | 'size' | 'content' | 'other' }
|
|
636
|
+
* | { kind: 'metadata', mode: 'any' | 'access-time' | 'write-time' | 'permissions' | 'ownership' | 'extended' | 'other' }
|
|
637
|
+
* | { kind: 'rename', mode: 'any' | 'to' | 'from' | 'both' | 'other' }
|
|
638
|
+
* | { kind: 'other' }} WatchEventKindModify
|
|
639
|
+
*/
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* 删掉了什么(对标 Tauri 的 `WatchEventKindRemove`)。
|
|
643
|
+
*
|
|
644
|
+
* @typedef {{ kind: 'any' } | { kind: 'file' } | { kind: 'folder' } | { kind: 'other' }} WatchEventKindRemove
|
|
645
|
+
*/
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* 变化的种类(对标 Tauri 的 `WatchEventKind`)。
|
|
649
|
+
*
|
|
650
|
+
* @typedef {'any' | 'other'
|
|
651
|
+
* | { access: WatchEventKindAccess }
|
|
652
|
+
* | { create: WatchEventKindCreate }
|
|
653
|
+
* | { modify: WatchEventKindModify }
|
|
654
|
+
* | { remove: WatchEventKindRemove }} WatchEventKind
|
|
655
|
+
*/
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* 一次文件系统变化(对标 Tauri 的 `WatchEvent`)。
|
|
659
|
+
*
|
|
660
|
+
* @typedef {object} WatchEvent
|
|
661
|
+
* @property {WatchEventKind} type 变化的种类
|
|
662
|
+
* @property {string[]} paths 受影响的路径(**绝对路径**)
|
|
663
|
+
* @property {unknown} attrs 底层 watcher 的附加属性
|
|
664
|
+
*/
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* 停止监视(对标 Tauri 的 `UnwatchFn`)。同步调用,幂等。
|
|
668
|
+
*
|
|
669
|
+
* @typedef {() => void} UnwatchFn
|
|
670
|
+
*/
|
|
671
|
+
|
|
672
|
+
/**
|
|
673
|
+
* `watchImmediate` 的选项(对标 Tauri 的 `WatchOptions`)。
|
|
674
|
+
*
|
|
675
|
+
* @typedef {object} WatchOptions
|
|
676
|
+
* @property {boolean} [recursive] 目录是否递归(对单文件无意义)
|
|
677
|
+
* @property {number} [baseDir] 用 `BaseDirectory` 枚举把相对路径解析到对应目录
|
|
678
|
+
*/
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* `watch` 的选项(对标 Tauri 的 `DebouncedWatchOptions`)。
|
|
682
|
+
*
|
|
683
|
+
* @typedef {WatchOptions & { delayMs?: number }} DebouncedWatchOptions
|
|
684
|
+
*/
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* 把 `string | URL` 统一成路径字符串。
|
|
688
|
+
*
|
|
689
|
+
* @param {string} fnName
|
|
690
|
+
* @param {unknown} value
|
|
691
|
+
* @returns {string}
|
|
692
|
+
* @remarks
|
|
693
|
+
* `file:` URL 会转成路径(Windows 盘符与 UNC 都处理)。其他协议的 URL **当场拒**——
|
|
694
|
+
* 与 Tauri 的 `Must be a file URL.` 同一个姿态:静默当成路径会让
|
|
695
|
+
* `http://x/a` 变成当前目录下一个叫 `http:` 的目录。
|
|
696
|
+
*/
|
|
697
|
+
function watchPathOf(fnName, value) {
|
|
698
|
+
if (typeof value === 'string') {
|
|
699
|
+
if (value.length === 0) {
|
|
700
|
+
throw new TypeError(`${fnName}: 路径不能是空字符串。`);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
return value;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
if (value instanceof URL) {
|
|
707
|
+
if (value.protocol !== 'file:') {
|
|
708
|
+
throw new TypeError(`${fnName}: 只接受 file: URL(收到 ${value.protocol})。`);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
let path;
|
|
712
|
+
try {
|
|
713
|
+
path = decodeURIComponent(value.pathname);
|
|
714
|
+
} catch {
|
|
715
|
+
throw new TypeError(`${fnName}: URL 的百分号编码不合法(${value.href})。`);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
// Windows 盘符:/C:/dir → C:/dir
|
|
719
|
+
if (/^\/[A-Za-z]:/.test(path)) {
|
|
720
|
+
path = path.slice(1);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// UNC:file://server/share → //server/share
|
|
724
|
+
return value.host ? `//${value.host}${path}` : path;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
throw new TypeError(
|
|
728
|
+
`${fnName}: paths 的元素必须是字符串或 URL,收到 ${value === null ? 'null' : typeof value}。`);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* 监视一批路径(对标 Tauri 的 `watch`)。
|
|
733
|
+
*
|
|
734
|
+
* @param {string | URL | Array<string | URL>} paths 要监视的路径
|
|
735
|
+
* @param {(event: WatchEvent) => void} cb 收到变化时调用
|
|
736
|
+
* @param {DebouncedWatchOptions} [options]
|
|
737
|
+
* @returns {Promise<UnwatchFn>} 停止监视的函数
|
|
738
|
+
* @remarks
|
|
739
|
+
* <b>合并窗口</b>:默认 `delayMs = 2000`(与 Tauri 一致)。窗口内的变化先攒着,
|
|
740
|
+
* 窗口结束再发;<b>按路径合并、后来的种类覆盖先前的</b>("先建后改"最终报 `modify`),
|
|
741
|
+
* 重命名按 `(旧, 新)` 单独成条。这不是 `notify-debouncer-full` 的逐字段合并算法,
|
|
742
|
+
* 但保证"一个路径不会在窗口里报两次"。
|
|
743
|
+
*
|
|
744
|
+
* ```js
|
|
745
|
+
* const unwatch = await watch('logs', (event) => {
|
|
746
|
+
* console.log(event.type, event.paths);
|
|
747
|
+
* }, { baseDir: BaseDirectory.AppLog, recursive: true });
|
|
748
|
+
* // 用完停掉
|
|
749
|
+
* unwatch();
|
|
750
|
+
* ```
|
|
751
|
+
*
|
|
752
|
+
* <b>事件只回给发起监视的那个窗口</b>(Tauri 的 Channel 同样绑在调用方 webview 上)。
|
|
753
|
+
* 窗口关闭后监视器仍然存在(事件没有收件人),直到 `unwatch()` 或应用退出——
|
|
754
|
+
* 监视不该因为页面导航这类与用户意图无关的事情被悄悄取消。
|
|
755
|
+
*
|
|
756
|
+
* 需要能力声明(`fs.watch`)与**每一个路径的 scope**。
|
|
757
|
+
*/
|
|
758
|
+
export async function watch(paths, cb, options) {
|
|
759
|
+
return watchInternal('watch', paths, cb, { delayMs: 2000, ...options });
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* 监视一批路径,变化**立刻**上报(对标 Tauri 的 `watchImmediate`)。
|
|
764
|
+
*
|
|
765
|
+
* @param {string | URL | Array<string | URL>} paths
|
|
766
|
+
* @param {(event: WatchEvent) => void} cb
|
|
767
|
+
* @param {WatchOptions} [options]
|
|
768
|
+
* @returns {Promise<UnwatchFn>}
|
|
769
|
+
* @remarks
|
|
770
|
+
* 与 {@link watch} 的唯一差别是**没有合并窗口**:一次保存被系统拆成三条事件,这里就收到三条
|
|
771
|
+
* (Windows 上很常见:`Changed` 会来两次)。要"一次保存只处理一次"就用 {@link watch}。
|
|
772
|
+
*
|
|
773
|
+
* 需要能力声明(`fs.watch`)与**每一个路径的 scope**。
|
|
774
|
+
*/
|
|
775
|
+
export async function watchImmediate(paths, cb, options) {
|
|
776
|
+
return watchInternal('watchImmediate', paths, cb, options);
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* `watch` 与 `watchImmediate` 的共同实现。
|
|
781
|
+
*
|
|
782
|
+
* @param {string} fnName
|
|
783
|
+
* @param {string | URL | Array<string | URL>} paths
|
|
784
|
+
* @param {(event: WatchEvent) => void} cb
|
|
785
|
+
* @param {Record<string, unknown> | null | undefined} options
|
|
786
|
+
* @returns {Promise<UnwatchFn>}
|
|
787
|
+
*/
|
|
788
|
+
async function watchInternal(fnName, paths, cb, options) {
|
|
789
|
+
if (typeof cb !== 'function') {
|
|
790
|
+
throw new TypeError(`${fnName}: 第二个参数必须是回调函数。`);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
const isDebounced = fnName === 'watch';
|
|
794
|
+
const problem = checkOptions(fnName, options, isDebounced ? ['recursive', 'delayMs'] : ['recursive']);
|
|
795
|
+
if (problem !== null) {
|
|
796
|
+
throw problem;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
const list = Array.isArray(paths) ? paths : [paths];
|
|
800
|
+
if (list.length === 0) {
|
|
801
|
+
throw new TypeError(`${fnName}: paths 至少要有一个路径。`);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** @type {string[]} */
|
|
805
|
+
const resolved = [];
|
|
806
|
+
for (const entry of list) {
|
|
807
|
+
// resolveAgainstBase 的返回类型是 unknown(它对"不是字符串就原样返回"),
|
|
808
|
+
// 而这里入参已经保证是字符串
|
|
809
|
+
resolved.push(/** @type {string} */ (await resolveAgainstBase(fnName, watchPathOf(fnName, entry), options)));
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** @type {Record<string, unknown>} */
|
|
813
|
+
const args = { paths: resolved };
|
|
814
|
+
|
|
815
|
+
const recursive = options?.recursive;
|
|
816
|
+
if (recursive !== undefined) {
|
|
817
|
+
args.recursive = Boolean(recursive);
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (isDebounced) {
|
|
821
|
+
const delayMs = options?.delayMs;
|
|
822
|
+
if (delayMs !== undefined) {
|
|
823
|
+
if (typeof delayMs !== 'number' || !Number.isInteger(delayMs) || delayMs < 0) {
|
|
824
|
+
throw new TypeError(`${fnName}: delayMs 必须是非负整数(毫秒),收到 ${String(delayMs)}。`);
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
args.delayMs = delayMs;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
const id = await invoke('fs.watch', args);
|
|
832
|
+
const transport = getTransport();
|
|
833
|
+
if (typeof transport.on !== 'function') {
|
|
834
|
+
throw new Error(`${fnName}: 当前传输层没有 on(),无法接收监视事件。`);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// 与 Channel 同一条通路:事件名里带编号,页面侧天然按监视器分流
|
|
838
|
+
const off = transport.on(`oriel://fs-watch/${id}`, (payload) => {
|
|
839
|
+
try {
|
|
840
|
+
cb(/** @type {WatchEvent} */ (payload));
|
|
841
|
+
} catch (error) {
|
|
842
|
+
// 回调抛错不该打断后续事件的投递(与桥接脚本对 oriel.on 的处理一致)
|
|
843
|
+
console.error(`${fnName} 的回调抛出`, error);
|
|
844
|
+
}
|
|
845
|
+
});
|
|
846
|
+
|
|
847
|
+
let stopped = false;
|
|
848
|
+
|
|
849
|
+
return () => {
|
|
850
|
+
if (stopped) {
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
stopped = true;
|
|
855
|
+
off();
|
|
856
|
+
|
|
857
|
+
// 停止命令是异步的,而 UnwatchFn 按 Tauri 的形状是同步的(返回 void)——
|
|
858
|
+
// 失败只进控制台:那一刻调用方已经在收尾,抛错也没有人接
|
|
859
|
+
void invoke('fs.unwatch', { id }).catch((error) => {
|
|
860
|
+
console.error(`${fnName}: 停止监视失败`, error);
|
|
861
|
+
});
|
|
862
|
+
};
|
|
863
|
+
}
|