@thedriveai/device-helper 0.0.0-stage → 0.1.4

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/dist/lib.js ADDED
@@ -0,0 +1,3036 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/lib.ts
31
+ var lib_exports = {};
32
+ __export(lib_exports, {
33
+ DEVICE_NAMESPACE: () => DEVICE_NAMESPACE,
34
+ DEVICE_PROTOCOL_VERSION: () => DEVICE_PROTOCOL_VERSION,
35
+ DeviceClient: () => DeviceClient,
36
+ HELPER_VERSION: () => HELPER_VERSION,
37
+ RootOps: () => RootOps,
38
+ bringUpRoot: () => bringUpRoot,
39
+ defaultDeviceName: () => defaultDeviceName,
40
+ deviceHome: () => deviceHome,
41
+ devicePlatform: () => devicePlatform,
42
+ loadConfig: () => loadConfig,
43
+ newRootId: () => newRootId,
44
+ rootHasTrash: () => rootHasTrash,
45
+ saveConfig: () => saveConfig,
46
+ stateDir: () => stateDir
47
+ });
48
+ module.exports = __toCommonJS(lib_exports);
49
+
50
+ // src/index.ts
51
+ var import_fs15 = __toESM(require("fs"));
52
+ var import_socket = require("socket.io-client");
53
+
54
+ // src/config.ts
55
+ var import_fs2 = __toESM(require("fs"));
56
+ var import_os = __toESM(require("os"));
57
+ var import_path2 = __toESM(require("path"));
58
+ var import_crypto = require("crypto");
59
+
60
+ // src/nasFolders.ts
61
+ var import_fs = __toESM(require("fs"));
62
+ var import_path = __toESM(require("path"));
63
+ var NAS_RECYCLE_BINS = [
64
+ { vendor: "QNAP", name: "@Recycle" },
65
+ { vendor: "Synology", name: "#recycle" }
66
+ ];
67
+ var FALLBACK_BIN = NAS_RECYCLE_BINS.find((b) => b.vendor === "Synology");
68
+ var NAS_SNAPSHOT_FOLDERS = ["#snapshot", "@Recently-Snapshot"];
69
+ var HOUSEKEEPING = new Set([...NAS_RECYCLE_BINS.map((b) => b.name), ...NAS_SNAPSHOT_FOLDERS].map((n) => n.toLowerCase()));
70
+ function isNasHousekeepingName(name) {
71
+ return HOUSEKEEPING.has(name.toLowerCase());
72
+ }
73
+ function isNasRecycleBinName(name) {
74
+ return NAS_RECYCLE_BINS.some((b) => b.name.toLowerCase() === name.toLowerCase());
75
+ }
76
+ function shareRecycleBin(rootPath, itemAbs) {
77
+ let root = import_path.default.resolve(rootPath);
78
+ try {
79
+ root = import_fs.default.realpathSync(root);
80
+ } catch {
81
+ }
82
+ for (let dir = import_path.default.dirname(import_path.default.resolve(itemAbs)); dir === root || dir.startsWith(root + import_path.default.sep); dir = import_path.default.dirname(dir)) {
83
+ for (const known of NAS_RECYCLE_BINS) {
84
+ const bin = import_path.default.join(dir, known.name);
85
+ if (import_fs.default.statSync(bin, { throwIfNoEntry: false })?.isDirectory()) return { bin, owner: dir };
86
+ }
87
+ if (dir === root) break;
88
+ }
89
+ return { bin: import_path.default.join(root, FALLBACK_BIN.name), owner: root };
90
+ }
91
+
92
+ // src/config.ts
93
+ function deviceHome() {
94
+ if (process.env.TDAI_DEVICE_HOME) return process.env.TDAI_DEVICE_HOME;
95
+ if (process.env.TDAI_DOCKER === "1" && import_fs2.default.existsSync("/config")) return "/config";
96
+ return import_path2.default.join(import_os.default.homedir(), ".thedrive-device");
97
+ }
98
+ function configPath(home = deviceHome()) {
99
+ return import_path2.default.join(home, "config.json");
100
+ }
101
+ function stateDir(rootId, home = deviceHome()) {
102
+ return import_path2.default.join(home, "state", rootId);
103
+ }
104
+ function devicePlatform() {
105
+ if (process.env.TDAI_DOCKER === "1") return "docker";
106
+ return process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "win32" : "linux";
107
+ }
108
+ function defaultDeviceName() {
109
+ return process.env.TDAI_DEVICE_NAME || import_os.default.hostname().replace(/\.local$/, "") || "device";
110
+ }
111
+ function loadConfig(home = deviceHome()) {
112
+ const file = configPath(home);
113
+ if (!import_fs2.default.existsSync(file)) {
114
+ return { deviceId: (0, import_crypto.randomUUID)(), name: defaultDeviceName(), server: process.env.TDAI_SERVER || "https://service.thedrive.ai", connectionId: null, workspaceId: null, token: null, roots: [] };
115
+ }
116
+ const parsed = JSON.parse(import_fs2.default.readFileSync(file, "utf8"));
117
+ return {
118
+ deviceId: typeof parsed.deviceId === "string" ? parsed.deviceId : (0, import_crypto.randomUUID)(),
119
+ name: typeof parsed.name === "string" && parsed.name ? parsed.name : defaultDeviceName(),
120
+ server: typeof parsed.server === "string" && parsed.server ? parsed.server : process.env.TDAI_SERVER || "https://service.thedrive.ai",
121
+ connectionId: typeof parsed.connectionId === "string" ? parsed.connectionId : null,
122
+ workspaceId: typeof parsed.workspaceId === "string" ? parsed.workspaceId : null,
123
+ token: typeof parsed.token === "string" ? parsed.token : null,
124
+ roots: Array.isArray(parsed.roots) ? parsed.roots.filter((r) => !!r && typeof r.id === "string" && typeof r.path === "string").map((r) => ({ id: r.id, label: r.label || import_path2.default.basename(r.path), path: r.path, ...rootTrash(r), readOnly: r.readOnly === true, content: r.content === "names" ? "names" : "documents", shared: r.shared === true, transient: r.transient === true })) : []
125
+ };
126
+ }
127
+ function rootTrash(r) {
128
+ if (r.trash === "share" || r.trash === "none") return { trash: r.trash };
129
+ if (r.trash !== "dir") return { trash: "os" };
130
+ if (r.trashDir && import_path2.default.dirname(import_path2.default.resolve(r.trashDir)) === import_path2.default.resolve(r.path) && isNasRecycleBinName(import_path2.default.basename(r.trashDir))) return { trash: "share" };
131
+ return { trash: "dir", trashDir: r.trashDir };
132
+ }
133
+ function saveConfig(config, home = deviceHome()) {
134
+ import_fs2.default.mkdirSync(home, { recursive: true });
135
+ const file = configPath(home);
136
+ const tmp = `${file}.${process.pid}.tmp`;
137
+ import_fs2.default.writeFileSync(tmp, JSON.stringify(config, null, 2), { mode: 384 });
138
+ import_fs2.default.renameSync(tmp, file);
139
+ }
140
+ function newRootId(existing) {
141
+ for (; ; ) {
142
+ const id = (0, import_crypto.randomUUID)().replace(/-/g, "").slice(0, 12);
143
+ if (!existing.some((r) => r.id === id)) return id;
144
+ }
145
+ }
146
+
147
+ // protocol.ts (shared with the server)
148
+ var DEVICE_PROTOCOL_VERSION = 2;
149
+ var DEVICE_NAMESPACE = "/devices";
150
+ var STREAM_CHUNK_BYTES = 256 * 1024;
151
+ var DEVICE_FOLDER_MIME = "application/vnd.thedrive.folder";
152
+ function normalizeDevicePath(input) {
153
+ const slashed = input.replace(/\\/g, "/").replace(/\/+/g, "/");
154
+ const trimmed = slashed.replace(/\/+$/, "");
155
+ if (!trimmed || trimmed === "/") return "";
156
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
157
+ }
158
+ function deviceDirname(path14) {
159
+ const p = normalizeDevicePath(path14);
160
+ const at = p.lastIndexOf("/");
161
+ return at <= 0 ? "" : p.slice(0, at);
162
+ }
163
+ function deviceBasename(path14) {
164
+ const p = normalizeDevicePath(path14);
165
+ return p.slice(p.lastIndexOf("/") + 1);
166
+ }
167
+ function deviceJoin(folder, name) {
168
+ return normalizeDevicePath(`${normalizeDevicePath(folder)}/${name}`);
169
+ }
170
+ function isSafeDevicePath(path14) {
171
+ if (path14 === "") return true;
172
+ if (!path14.startsWith("/")) return false;
173
+ return path14.slice(1).split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".." && !segment.includes("\0"));
174
+ }
175
+
176
+ // src/journal.ts
177
+ var import_fs6 = __toESM(require("fs"));
178
+ var import_path6 = __toESM(require("path"));
179
+ var import_crypto2 = require("crypto");
180
+
181
+ // src/walker.ts
182
+ var import_fs5 = __toESM(require("fs"));
183
+ var import_path5 = __toESM(require("path"));
184
+
185
+ // src/fsitems.ts
186
+ var import_fs3 = __toESM(require("fs"));
187
+ var import_path3 = __toESM(require("path"));
188
+ var PathError = class extends Error {
189
+ constructor(code, message) {
190
+ super(message);
191
+ this.code = code;
192
+ this.name = "PathError";
193
+ }
194
+ };
195
+ var IGNORED_NAMES = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", "desktop.ini", "@eaDir", "$RECYCLE.BIN", "System Volume Information", ".Trashes", ".Trash", ".Spotlight-V100", ".fseventsd", ".TemporaryItems", "lost+found", "node_modules", ".git", "__pycache__", "site-packages", "bower_components"]);
196
+ var TRASH_MARKER = ".thedrive-trash";
197
+ var DEPENDENCY_MARKERS = ["pyvenv.cfg", TRASH_MARKER];
198
+ function isIgnoredName(name) {
199
+ if (process.platform !== "win32" && name.includes("\\")) return true;
200
+ return name.startsWith(".") || IGNORED_NAMES.has(name) || isNasHousekeepingName(name) || name.startsWith("~$") || name.endsWith(".crdownload") || name.endsWith(".part") || name.endsWith(".tmp");
201
+ }
202
+ function isDependencyFolder(abs) {
203
+ for (const marker of DEPENDENCY_MARKERS) if (import_fs3.default.existsSync(import_path3.default.join(abs, marker))) return true;
204
+ return false;
205
+ }
206
+ function isIgnoredDevicePath(rootReal, device, cache) {
207
+ const segments = device.split("/").filter(Boolean);
208
+ if (segments.some(isIgnoredName)) return true;
209
+ for (let i = 1; i <= segments.length; i += 1) {
210
+ const folder = import_path3.default.join(rootReal, ...segments.slice(0, i));
211
+ let dependency = cache?.get(folder);
212
+ if (dependency === void 0) {
213
+ dependency = isDependencyFolder(folder);
214
+ cache?.set(folder, dependency);
215
+ }
216
+ if (dependency) return true;
217
+ }
218
+ return false;
219
+ }
220
+ function resolveUnder(rootPath, devicePath, options = {}) {
221
+ const device = normalizeDevicePath(devicePath);
222
+ if (!isSafeDevicePath(device)) throw new PathError("BAD_PATH", `not a valid path: ${devicePath}`);
223
+ const rootReal = import_fs3.default.realpathSync(rootPath);
224
+ if (device === "") return { device, abs: rootReal };
225
+ const segments = device.slice(1).split("/");
226
+ if (segments.some(isIgnoredName)) throw new PathError("BAD_PATH", `${device} is a hidden or system path and is not shared`);
227
+ if (isIgnoredDevicePath(rootReal, device)) throw new PathError("BAD_PATH", `${device} is inside a dependency or trash folder and is not shared`);
228
+ const parentAbs = import_path3.default.join(rootReal, ...segments.slice(0, -1));
229
+ let parentReal;
230
+ try {
231
+ parentReal = import_fs3.default.realpathSync(parentAbs);
232
+ } catch {
233
+ throw new PathError("NOT_FOUND", `no such folder: ${deviceDirname(device) || "/"}`);
234
+ }
235
+ if (parentReal !== rootReal && !parentReal.startsWith(rootReal + import_path3.default.sep)) throw new PathError("BAD_PATH", `${device} points outside the shared folder`);
236
+ const abs = import_path3.default.join(parentReal, segments[segments.length - 1]);
237
+ if (options.mustExist) {
238
+ let stat;
239
+ try {
240
+ stat = import_fs3.default.lstatSync(abs);
241
+ } catch {
242
+ throw new PathError("NOT_FOUND", `no such item: ${device}`);
243
+ }
244
+ if (stat.isSymbolicLink()) {
245
+ let target;
246
+ try {
247
+ target = import_fs3.default.realpathSync(abs);
248
+ } catch {
249
+ throw new PathError("NOT_FOUND", `${device} is a broken link`);
250
+ }
251
+ if (target !== rootReal && !target.startsWith(rootReal + import_path3.default.sep)) throw new PathError("BAD_PATH", `${device} links outside the shared folder`);
252
+ }
253
+ }
254
+ return { device, abs };
255
+ }
256
+ function itemFor(devicePath, stat, nameOverride) {
257
+ const device = normalizeDevicePath(devicePath);
258
+ const name = nameOverride ?? deviceBasename(device);
259
+ if (device !== "" && isIgnoredName(name)) return null;
260
+ const kind = stat.isDirectory() ? "folder" : stat.isFile() ? "file" : null;
261
+ if (!kind) return null;
262
+ return {
263
+ externalId: device,
264
+ parentExternalId: device === "" ? null : deviceDirname(device),
265
+ name,
266
+ kind,
267
+ // The server derives a file's type from its name (DeviceSource.itemFromDevice); the helper ships no mime table.
268
+ mimeType: kind === "folder" ? DEVICE_FOLDER_MIME : "application/octet-stream",
269
+ size: kind === "file" ? stat.size : null,
270
+ mtime: stat.mtime.toISOString(),
271
+ ctime: stat.birthtime && stat.birthtime.getTime() > 0 ? stat.birthtime.toISOString() : null,
272
+ contentHash: null,
273
+ ownerEmail: null,
274
+ webUrl: null,
275
+ trashed: false
276
+ };
277
+ }
278
+ function statOrNull(abs) {
279
+ try {
280
+ return import_fs3.default.statSync(abs);
281
+ } catch {
282
+ return null;
283
+ }
284
+ }
285
+
286
+ // src/placeholders.ts
287
+ var import_fs4 = __toESM(require("fs"));
288
+ var import_path4 = __toESM(require("path"));
289
+
290
+ // src/exec.ts
291
+ var import_child_process = require("child_process");
292
+ function runFile(file, args, options = {}) {
293
+ return new Promise((resolve, reject) => (0, import_child_process.execFile)(file, args, {
294
+ timeout: options.timeoutMs ?? 3e4,
295
+ maxBuffer: options.maxBuffer ?? 64 * 1024 * 1024,
296
+ windowsHide: true,
297
+ ...options.env ? { env: { ...process.env, ...options.env } } : {}
298
+ }, (error, stdout, stderr) => {
299
+ if (!error) {
300
+ resolve(stdout.toString());
301
+ return;
302
+ }
303
+ const said = stderr?.toString().trim();
304
+ reject(Object.assign(new Error(said || error.message), { code: error.code }));
305
+ }));
306
+ }
307
+ function powershellVar(name) {
308
+ if (!/^[A-Z][A-Z0-9_]*$/.test(name)) throw new Error(`not a PowerShell value name: ${name}`);
309
+ return `TDAI_PS_${name}`;
310
+ }
311
+ function powershellInvocation(script, values = {}) {
312
+ const env = {};
313
+ for (const [name, value] of Object.entries(values)) {
314
+ if (value.length >= 3 && script.includes(value)) throw new Error(`the value of ${name} appears in the script text`);
315
+ env[powershellVar(name)] = value;
316
+ }
317
+ const full = `$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${script}`;
318
+ return { file: "powershell.exe", args: ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", Buffer.from(full, "utf16le").toString("base64")], env };
319
+ }
320
+ function runPowerShell(script, values = {}, options = {}) {
321
+ const call = powershellInvocation(script, values);
322
+ return runFile(call.file, call.args, { ...options, env: call.env });
323
+ }
324
+
325
+ // src/placeholders.ts
326
+ var SF_DATALESS = 1073741824;
327
+ var WIN_PLACEHOLDER_MASK = 4096 | 4194304 | 262144;
328
+ function icloudStubName(entryName) {
329
+ const m = /^\.(.+)\.icloud$/.exec(entryName);
330
+ return m ? m[1] : null;
331
+ }
332
+ var Placeholders = class {
333
+ constructor(rootReal, platform = process.platform) {
334
+ this.rootReal = rootReal;
335
+ this.platform = platform;
336
+ }
337
+ dataless = /* @__PURE__ */ new Set();
338
+ /** Whether the OS was asked at all (false on a platform without placeholders, or when the scan failed). */
339
+ scanned = false;
340
+ /** Ask the OS for every placeholder under the root. Idempotent; a failed scan leaves the last answer. */
341
+ async refresh() {
342
+ try {
343
+ if (this.platform === "darwin") {
344
+ const out = await runFile("/usr/bin/find", [this.rootReal, "-flags", "+dataless", "-print0"], { maxBuffer: 256 * 1024 * 1024, timeoutMs: 10 * 6e4 });
345
+ this.dataless = new Set(out.split("\0").filter(Boolean));
346
+ } else if (this.platform === "win32") {
347
+ const script = `Get-ChildItem -LiteralPath $env:TDAI_PS_ROOT -Recurse -Force -File -ErrorAction SilentlyContinue | Where-Object { ($_.Attributes -band ${WIN_PLACEHOLDER_MASK}) -ne 0 } | ForEach-Object { $_.FullName }`;
348
+ const out = await runPowerShell(script, { ROOT: this.rootReal }, { maxBuffer: 256 * 1024 * 1024, timeoutMs: 10 * 6e4 });
349
+ this.dataless = new Set(out.split(/\r?\n/).filter(Boolean));
350
+ } else {
351
+ this.dataless = /* @__PURE__ */ new Set();
352
+ }
353
+ this.scanned = true;
354
+ } catch {
355
+ }
356
+ return this.dataless.size;
357
+ }
358
+ has(abs) {
359
+ return this.dataless.has(abs);
360
+ }
361
+ /** Re-check one file after a change: the OS may have fetched or evicted it. */
362
+ async check(abs) {
363
+ try {
364
+ if (this.platform === "darwin") {
365
+ const out = await runFile("/usr/bin/stat", ["-f", "%f", abs], { maxBuffer: 64 * 1024 });
366
+ const flags = Number.parseInt(out.trim(), 10);
367
+ const yes = Number.isFinite(flags) && (flags & SF_DATALESS) !== 0;
368
+ if (yes) this.dataless.add(abs);
369
+ else this.dataless.delete(abs);
370
+ return yes;
371
+ }
372
+ if (this.platform === "win32") {
373
+ const out = await runPowerShell("(Get-Item -LiteralPath $env:TDAI_PS_PATH -Force).Attributes.value__", { PATH: abs }, { maxBuffer: 64 * 1024 });
374
+ const attrs = Number.parseInt(out.trim(), 10);
375
+ const yes = Number.isFinite(attrs) && (attrs & WIN_PLACEHOLDER_MASK) !== 0;
376
+ if (yes) this.dataless.add(abs);
377
+ else this.dataless.delete(abs);
378
+ return yes;
379
+ }
380
+ } catch {
381
+ }
382
+ return this.dataless.has(abs);
383
+ }
384
+ get count() {
385
+ return this.dataless.size;
386
+ }
387
+ get known() {
388
+ return this.scanned;
389
+ }
390
+ /** Test seam: mark paths as placeholders without asking the OS. */
391
+ setForTests(paths) {
392
+ const real = (p) => {
393
+ try {
394
+ return import_fs4.default.realpathSync(p);
395
+ } catch {
396
+ return import_path4.default.resolve(p);
397
+ }
398
+ };
399
+ this.dataless = new Set(paths.map(real));
400
+ this.scanned = true;
401
+ }
402
+ };
403
+ var registry = /* @__PURE__ */ new Map();
404
+ function placeholdersFor(rootReal) {
405
+ let p = registry.get(rootReal);
406
+ if (!p) {
407
+ p = new Placeholders(rootReal);
408
+ registry.set(rootReal, p);
409
+ }
410
+ return p;
411
+ }
412
+
413
+ // src/walker.ts
414
+ var PAGE_MAX_BYTES = 256 * 1024;
415
+ function wireBytes(value) {
416
+ return Buffer.byteLength(JSON.stringify(value)) + 1;
417
+ }
418
+ var FolderUnreadableError = class extends Error {
419
+ constructor(abs, code) {
420
+ super(`could not read ${abs} (${code})`);
421
+ this.abs = abs;
422
+ this.code = code;
423
+ this.name = "FolderUnreadableError";
424
+ }
425
+ };
426
+ var FolderDeniedError = class extends FolderUnreadableError {
427
+ constructor(abs) {
428
+ super(abs, "EACCES");
429
+ this.message = `not allowed to read ${abs}`;
430
+ this.name = "FolderDeniedError";
431
+ }
432
+ };
433
+ function compareEntries(a, b) {
434
+ if (a.kind !== b.kind) return a.kind === "folder" ? -1 : 1;
435
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
436
+ }
437
+ function folderAbs(rootReal, folderDevice) {
438
+ return folderDevice === "" ? rootReal : import_path5.default.join(rootReal, ...folderDevice.slice(1).split("/"));
439
+ }
440
+ function idOf(stat) {
441
+ return stat && stat.isDirectory() && stat.ino ? `${stat.dev}:${stat.ino}` : null;
442
+ }
443
+ function errorState(error) {
444
+ const code = error.code ?? "EIO";
445
+ if (code === "ENOENT" || code === "ENOTDIR") return { state: "gone" };
446
+ return { state: "unreadable", code, denied: code === "EPERM" || code === "EACCES" };
447
+ }
448
+ async function readFolder(rootReal, folderDevice, after = null, options = {}) {
449
+ const abs = folderAbs(rootReal, folderDevice);
450
+ const placeholders = placeholdersFor(rootReal);
451
+ const passed = (p) => !!after && compareEntries(p, after) <= 0;
452
+ const entries = [];
453
+ try {
454
+ const dir = await import_fs5.default.promises.opendir(abs);
455
+ for await (const entry of dir) {
456
+ const stub = icloudStubName(entry.name);
457
+ if (stub) {
458
+ if (isIgnoredName(stub) || passed({ kind: "file", name: stub })) continue;
459
+ const stubStat = statOrNull(import_path5.default.join(abs, entry.name));
460
+ const item2 = stubStat ? itemFor(deviceJoin(folderDevice, stub), stubStat, stub) : null;
461
+ if (item2) entries.push({ item: { ...item2, kind: "file", size: null, onlineOnly: true }, id: null });
462
+ continue;
463
+ }
464
+ if (isIgnoredName(entry.name)) continue;
465
+ const childAbs = import_path5.default.join(abs, entry.name);
466
+ const untyped = !entry.isDirectory() && !entry.isFile() && !entry.isSymbolicLink() && !entry.isFIFO() && !entry.isSocket() && !entry.isBlockDevice() && !entry.isCharacterDevice();
467
+ let isLink = entry.isSymbolicLink();
468
+ if (untyped) {
469
+ try {
470
+ isLink = import_fs5.default.lstatSync(childAbs).isSymbolicLink();
471
+ } catch {
472
+ continue;
473
+ }
474
+ }
475
+ let stat;
476
+ if (isLink) {
477
+ let target;
478
+ try {
479
+ target = import_fs5.default.realpathSync(childAbs);
480
+ } catch {
481
+ continue;
482
+ }
483
+ if (target !== rootReal && !target.startsWith(rootReal + import_path5.default.sep)) continue;
484
+ stat = statOrNull(childAbs);
485
+ } else if (entry.isDirectory() || entry.isFile() || untyped) {
486
+ if (!untyped && passed({ kind: entry.isDirectory() ? "folder" : "file", name: entry.name })) continue;
487
+ stat = statOrNull(childAbs);
488
+ } else {
489
+ continue;
490
+ }
491
+ if (!stat) continue;
492
+ if (stat.isDirectory() && isDependencyFolder(childAbs)) {
493
+ options.onSkipped?.(deviceJoin(folderDevice, entry.name));
494
+ continue;
495
+ }
496
+ const item = itemFor(deviceJoin(folderDevice, entry.name), stat, entry.name);
497
+ if (!item || passed(item)) continue;
498
+ entries.push({ item: item.kind === "file" && placeholders.has(childAbs) ? { ...item, onlineOnly: true } : item, id: idOf(stat) });
499
+ }
500
+ } catch (error) {
501
+ return errorState(error);
502
+ }
503
+ entries.sort((a, b) => compareEntries(a.item, b.item));
504
+ return { state: "listed", entries };
505
+ }
506
+ async function openFrame(rootReal, device, after, options) {
507
+ const read = await readFolder(rootReal, device, after, { onSkipped: options.onSkipped });
508
+ if (read.state === "listed") {
509
+ options.onFolder?.(folderAbs(rootReal, device));
510
+ return { id: idOf(statOrNull(folderAbs(rootReal, device))), entries: read.entries, next: 0 };
511
+ }
512
+ if (read.state === "unreadable") options.onUnreadable?.(device);
513
+ return null;
514
+ }
515
+ async function* walkFrames(rootReal, stack, above, options) {
516
+ while (stack.length) {
517
+ const top = stack[stack.length - 1];
518
+ if (top.next >= top.entries.length) {
519
+ stack.pop();
520
+ continue;
521
+ }
522
+ const { item, id } = top.entries[top.next++];
523
+ if (item.kind === "folder" && id && (above.has(id) || stack.some((f) => f.id === id))) continue;
524
+ yield item;
525
+ if (item.kind === "folder") {
526
+ const child = await openFrame(rootReal, item.externalId, null, options);
527
+ if (child) stack.push(child);
528
+ }
529
+ }
530
+ }
531
+ function idsAbove(rootReal, folderDevice) {
532
+ const ids = /* @__PURE__ */ new Set();
533
+ const segments = folderDevice ? folderDevice.slice(1).split("/") : [];
534
+ for (let i = 0; i <= segments.length; i += 1) {
535
+ const id = idOf(statOrNull(folderAbs(rootReal, i ? `/${segments.slice(0, i).join("/")}` : "")));
536
+ if (id) ids.add(id);
537
+ }
538
+ return ids;
539
+ }
540
+ async function* walkAll(rootPath, folderDevice, options = {}) {
541
+ const rootReal = import_fs5.default.realpathSync(rootPath);
542
+ const read = await readFolder(rootReal, folderDevice, null, { onSkipped: options.onSkipped });
543
+ if (read.state !== "listed") {
544
+ options.onUnreadable?.(folderDevice);
545
+ return;
546
+ }
547
+ const start = { id: idOf(statOrNull(folderAbs(rootReal, folderDevice))), entries: read.entries, next: 0 };
548
+ yield* walkFrames(rootReal, [start], idsAbove(rootReal, folderDevice), options);
549
+ }
550
+ var WALK_CURSOR_VERSION = 2;
551
+ function readWalkCursor(cursor) {
552
+ if (!cursor) return null;
553
+ try {
554
+ const parsed = JSON.parse(cursor);
555
+ if (parsed.v !== WALK_CURSOR_VERSION) return null;
556
+ return typeof parsed.at === "string" && parsed.at.startsWith("/") ? { at: parsed.at, folder: parsed.folder === true } : null;
557
+ } catch {
558
+ return null;
559
+ }
560
+ }
561
+ function writeWalkCursor(cursor) {
562
+ return JSON.stringify({ v: WALK_CURSOR_VERSION, ...cursor });
563
+ }
564
+ async function framesAt(rootReal, cursor, options) {
565
+ const openRoot = async (after) => {
566
+ const read = await readFolder(rootReal, "", after, { onSkipped: options.onSkipped });
567
+ if (read.state !== "listed") throw read.state === "unreadable" && read.denied ? new FolderDeniedError(rootReal) : new FolderUnreadableError(rootReal, read.state === "unreadable" ? read.code : "ENOENT");
568
+ return { id: idOf(statOrNull(rootReal)), entries: read.entries, next: 0 };
569
+ };
570
+ if (!cursor) return [await openRoot(null)];
571
+ const segments = cursor.at.slice(1).split("/");
572
+ const stack = [];
573
+ const markers = /* @__PURE__ */ new Map();
574
+ for (let i = 0; i < segments.length; i += 1) {
575
+ const device = i ? `/${segments.slice(0, i).join("/")}` : "";
576
+ if (i && isIgnoredDevicePath(rootReal, device, markers)) return stack;
577
+ const kind = i < segments.length - 1 || cursor.folder ? "folder" : "file";
578
+ const frame = i ? await openFrame(rootReal, device, { kind, name: segments[i] }, options) : await openRoot({ kind, name: segments[i] });
579
+ if (!frame) return stack;
580
+ stack.push(frame);
581
+ }
582
+ if (cursor.folder && !isIgnoredDevicePath(rootReal, cursor.at, markers)) {
583
+ const inside = await openFrame(rootReal, cursor.at, null, options);
584
+ if (inside && !(inside.id && stack.some((f) => f.id === inside.id))) stack.push(inside);
585
+ }
586
+ return stack;
587
+ }
588
+ async function walkPage(rootPath, cursor, limit, options = {}) {
589
+ const rootReal = import_fs5.default.realpathSync(rootPath);
590
+ const maxBytes = options.maxBytes ?? PAGE_MAX_BYTES;
591
+ const unreadable = /* @__PURE__ */ new Set();
592
+ const tracked = { ...options, onUnreadable: (folder) => {
593
+ if (folder) unreadable.add(folder);
594
+ options.onUnreadable?.(folder);
595
+ } };
596
+ const stack = await framesAt(rootReal, readWalkCursor(cursor), tracked);
597
+ const items = [];
598
+ let bytes = 0;
599
+ let last = null;
600
+ let more = false;
601
+ for await (const raw of walkFrames(rootReal, stack, /* @__PURE__ */ new Set(), tracked)) {
602
+ const item = options.map ? options.map(raw) : raw;
603
+ const size = wireBytes(item);
604
+ if (items.length && (items.length >= Math.max(1, limit) || bytes + size > maxBytes)) {
605
+ more = true;
606
+ break;
607
+ }
608
+ items.push(item);
609
+ bytes += size;
610
+ last = raw;
611
+ }
612
+ return { items, cursor: more && last ? writeWalkCursor({ at: last.externalId, folder: last.kind === "folder" }) : null, done: !more, ...unreadable.size ? { unreadable: [...unreadable] } : {} };
613
+ }
614
+ async function listPage(rootPath, folderDevice, cursor, limit, options = {}) {
615
+ const rootReal = import_fs5.default.realpathSync(rootPath);
616
+ const maxBytes = options.maxBytes ?? PAGE_MAX_BYTES;
617
+ let after = null;
618
+ let skip = 0;
619
+ if (cursor && /^\d+$/.test(cursor)) skip = Number(cursor);
620
+ else if (cursor) {
621
+ try {
622
+ const parsed = JSON.parse(cursor);
623
+ if (parsed.after && typeof parsed.after.name === "string") after = { kind: parsed.after.kind === "folder" ? "folder" : "file", name: parsed.after.name };
624
+ } catch {
625
+ }
626
+ }
627
+ const read = await readFolder(rootReal, folderDevice, after);
628
+ if (read.state === "unreadable") {
629
+ const abs = folderAbs(rootReal, folderDevice);
630
+ throw read.denied ? new FolderDeniedError(abs) : new FolderUnreadableError(abs, read.code);
631
+ }
632
+ const all = read.state === "listed" ? read.entries.slice(skip) : [];
633
+ const items = [];
634
+ let bytes = 0;
635
+ for (const { item: raw } of all) {
636
+ const item = options.map ? options.map(raw) : raw;
637
+ const size = wireBytes(item);
638
+ if (items.length && (items.length >= Math.max(1, limit) || bytes + size > maxBytes)) {
639
+ const lastSent = items[items.length - 1];
640
+ return { items, cursor: JSON.stringify({ after: { kind: lastSent.kind, name: lastSent.name } }) };
641
+ }
642
+ items.push(item);
643
+ bytes += size;
644
+ }
645
+ return { items, cursor: null };
646
+ }
647
+
648
+ // src/journal.ts
649
+ var JOURNAL_KEEP = 2e5;
650
+ var Journal = class {
651
+ constructor(dir, keep = JOURNAL_KEEP) {
652
+ this.dir = dir;
653
+ this.keep = keep;
654
+ this.file = import_path6.default.join(dir, "journal.jsonl");
655
+ }
656
+ epoch = "";
657
+ /** The last seq handed to an entry, on disk or not. */
658
+ seq = 0;
659
+ /** The last seq that is on disk: everything the journal serves stops here. */
660
+ durable = 0;
661
+ entries = [];
662
+ file;
663
+ /** Lines recorded and not yet written. */
664
+ unwritten = [];
665
+ /** The next write replaces the file with the kept tail (compaction) instead of appending. */
666
+ rewrite = false;
667
+ writing = null;
668
+ /** Told after entries land on disk (the host nudges the server, debounced; DEVICE_MOUNTS.md §14). */
669
+ onRecord = null;
670
+ /** Replay the file; a missing or unreadable one starts a new epoch. */
671
+ load() {
672
+ import_fs6.default.mkdirSync(this.dir, { recursive: true });
673
+ this.entries = [];
674
+ this.seq = 0;
675
+ this.epoch = "";
676
+ this.unwritten = [];
677
+ if (import_fs6.default.existsSync(this.file)) {
678
+ let raw = import_fs6.default.readFileSync(this.file);
679
+ const end = raw.lastIndexOf(10) + 1;
680
+ if (end < raw.length) {
681
+ import_fs6.default.truncateSync(this.file, end);
682
+ raw = raw.subarray(0, end);
683
+ }
684
+ for (const line of raw.toString("utf8").split("\n")) {
685
+ if (!line) continue;
686
+ let parsed;
687
+ try {
688
+ parsed = JSON.parse(line);
689
+ } catch {
690
+ continue;
691
+ }
692
+ if (typeof parsed.epoch === "string") {
693
+ this.epoch = parsed.epoch;
694
+ continue;
695
+ }
696
+ if (typeof parsed.seq !== "number" || typeof parsed.path !== "string") continue;
697
+ this.entries.push({ seq: parsed.seq, path: parsed.path, removed: !!parsed.removed, item: parsed.item ?? null, ...parsed.created ? { created: true } : {}, ...typeof parsed.movedFrom === "string" ? { movedFrom: parsed.movedFrom } : {}, ...parsed.recoverable === false ? { recoverable: false } : {} });
698
+ this.seq = Math.max(this.seq, parsed.seq);
699
+ }
700
+ }
701
+ if (!this.epoch) {
702
+ this.epoch = (0, import_crypto2.randomUUID)().replace(/-/g, "").slice(0, 10);
703
+ this.entries = [];
704
+ this.seq = 0;
705
+ writeDurably(this.file, `${JSON.stringify({ epoch: this.epoch })}
706
+ `);
707
+ }
708
+ this.durable = this.seq;
709
+ if (this.entries.length > this.keep) this.entries.splice(0, this.entries.length - this.keep);
710
+ }
711
+ /** The last durable position: what the server may hold as a cursor. */
712
+ get position() {
713
+ return `${this.epoch}:${this.durable}`;
714
+ }
715
+ /** How many entries the journal keeps: a change set larger than this cannot be replayed and is better re-enumerated. */
716
+ get keepCount() {
717
+ return this.keep;
718
+ }
719
+ /**
720
+ * Start a new epoch: every cursor the server holds is of the old one and answers `resetRequired`, so it
721
+ * re-enumerates. The designed answer to a change set the journal could not carry (a restore, a mass touch).
722
+ */
723
+ reset() {
724
+ this.epoch = (0, import_crypto2.randomUUID)().replace(/-/g, "").slice(0, 10);
725
+ this.entries = [];
726
+ this.seq = 0;
727
+ this.durable = 0;
728
+ this.unwritten = [];
729
+ this.rewrite = false;
730
+ writeDurably(this.file, `${JSON.stringify({ epoch: this.epoch })}
731
+ `);
732
+ try {
733
+ this.onRecord?.();
734
+ } catch {
735
+ }
736
+ }
737
+ record(change) {
738
+ this.seq += 1;
739
+ const entry = { seq: this.seq, path: change.path, removed: change.removed, item: change.removed ? null : change.item, ...change.created && !change.removed ? { created: true } : {}, ...change.movedFrom && !change.removed ? { movedFrom: change.movedFrom } : {}, ...change.removed && change.recoverable === false ? { recoverable: false } : {} };
740
+ this.entries.push(entry);
741
+ this.unwritten.push(JSON.stringify(entry));
742
+ if (this.entries.length > this.keep * 2) {
743
+ this.entries.splice(0, this.entries.length - this.keep);
744
+ this.rewrite = true;
745
+ }
746
+ this.writing ??= this.drain();
747
+ }
748
+ /** `created`: the path was not in the snapshot before (a new file or folder, not a rewrite). `movedFrom`: it was at that path. */
749
+ upsert(item, created = false, movedFrom) {
750
+ this.record({ path: item.externalId, removed: false, item, created, movedFrom });
751
+ }
752
+ /** `recoverable: false`: the path left the share by policy, not for the trash; the server drops its row. */
753
+ remove(devicePath, options = {}) {
754
+ this.record({ path: devicePath, removed: true, item: null, recoverable: options.recoverable });
755
+ }
756
+ /** Write what is pending, batch after batch, each fsync'd before its entries count. */
757
+ async drain() {
758
+ try {
759
+ await null;
760
+ while (this.unwritten.length || this.rewrite) {
761
+ const upTo = this.seq;
762
+ const lines = this.unwritten.splice(0);
763
+ try {
764
+ if (this.rewrite) {
765
+ this.rewrite = false;
766
+ const body = [JSON.stringify({ epoch: this.epoch }), ...this.entries.map((e) => JSON.stringify(e))].join("\n") + "\n";
767
+ await writeFileSynced(`${this.file}.tmp`, body, "w");
768
+ await import_fs6.default.promises.rename(`${this.file}.tmp`, this.file);
769
+ } else {
770
+ await writeFileSynced(this.file, `${lines.join("\n")}
771
+ `, "a");
772
+ }
773
+ } catch {
774
+ this.unwritten.unshift(...lines);
775
+ return;
776
+ }
777
+ this.durable = upTo;
778
+ try {
779
+ this.onRecord?.();
780
+ } catch {
781
+ }
782
+ }
783
+ } finally {
784
+ this.writing = null;
785
+ }
786
+ }
787
+ /** Changes after `cursor`, at most `limit` and PAGE_MAX_BYTES of them; '' asks for the current position only. */
788
+ since(cursor, limit, maxBytes = PAGE_MAX_BYTES) {
789
+ if (cursor === "") return { changes: [], cursor: this.position, done: true };
790
+ const at = cursor.indexOf(":");
791
+ const epoch = at > 0 ? cursor.slice(0, at) : "";
792
+ const seq = Number(cursor.slice(at + 1));
793
+ if (epoch !== this.epoch || !Number.isInteger(seq) || seq < 0) return { changes: [], cursor: this.position, done: true, resetRequired: true };
794
+ if (seq > this.durable) return { changes: [], cursor: this.position, done: true, resetRequired: true };
795
+ if (this.entries.length && seq < this.entries[0].seq - 1) return { changes: [], cursor: this.position, done: true, resetRequired: true };
796
+ const changes = [];
797
+ let last = seq;
798
+ let bytes = 0;
799
+ for (const entry of this.entries) {
800
+ if (entry.seq <= seq) continue;
801
+ if (entry.seq > this.durable) break;
802
+ const change = entry.removed ? { externalId: entry.path, removed: true, recoverable: entry.recoverable !== false, item: null } : { externalId: entry.path, removed: false, item: entry.item, ...entry.created ? { created: true } : {}, ...entry.movedFrom ? { movedFrom: entry.movedFrom } : {} };
803
+ const size = wireBytes(change);
804
+ if (changes.length && (changes.length >= Math.max(1, limit) || bytes + size > maxBytes)) break;
805
+ changes.push(change);
806
+ bytes += size;
807
+ last = entry.seq;
808
+ }
809
+ return { changes, cursor: `${this.epoch}:${last}`, done: last >= this.durable };
810
+ }
811
+ /** Wait until everything recorded so far is on disk (an op before it answers, a rescan before its snapshot, shutdown). */
812
+ async flush() {
813
+ while (this.writing) await this.writing;
814
+ if (this.unwritten.length) {
815
+ this.writing ??= this.drain();
816
+ await this.writing;
817
+ }
818
+ }
819
+ /** Test seam. */
820
+ get size() {
821
+ return this.entries.length;
822
+ }
823
+ };
824
+ async function writeFileSynced(file, body, flags) {
825
+ const handle = await import_fs6.default.promises.open(file, flags);
826
+ try {
827
+ await handle.writeFile(body);
828
+ await handle.sync();
829
+ } finally {
830
+ await handle.close();
831
+ }
832
+ }
833
+ function writeDurably(file, body) {
834
+ const fd = import_fs6.default.openSync(file, "w");
835
+ try {
836
+ import_fs6.default.writeSync(fd, body);
837
+ import_fs6.default.fsyncSync(fd);
838
+ } finally {
839
+ import_fs6.default.closeSync(fd);
840
+ }
841
+ }
842
+
843
+ // src/snapshot.ts
844
+ var import_fs7 = __toESM(require("fs"));
845
+ var import_path7 = __toESM(require("path"));
846
+ var PERSIST_SOON_MS = 3e4;
847
+ var MASS_REMOVAL_SHARE = 0.5;
848
+ var MASS_REMOVAL_MIN_ITEMS = 50;
849
+ var Snapshot = class _Snapshot {
850
+ file;
851
+ acceptFile;
852
+ entries = /* @__PURE__ */ new Map();
853
+ loaded = false;
854
+ /** While a walk runs: paths ops and the watcher set, and paths (with all below) they removed. */
855
+ touched = null;
856
+ running = null;
857
+ constructor(dir) {
858
+ this.file = import_path7.default.join(dir, "snapshot.jsonl");
859
+ this.acceptFile = acceptRemovalsFile(dir);
860
+ }
861
+ /** Whether a snapshot exists: without one the first walk only records, it reports nothing (the server enumerates). */
862
+ load() {
863
+ this.entries = /* @__PURE__ */ new Map();
864
+ this.loaded = import_fs7.default.existsSync(this.file);
865
+ if (!this.loaded) return false;
866
+ for (const line of import_fs7.default.readFileSync(this.file, "utf8").split("\n")) {
867
+ if (!line) continue;
868
+ try {
869
+ const parsed = JSON.parse(line);
870
+ if (typeof parsed.p === "string") this.entries.set(parsed.p, { k: parsed.k, s: parsed.s ?? null, m: parsed.m ?? null, ...typeof parsed.h === "string" ? { h: parsed.h } : {}, ...parsed.o ? { o: true } : {} });
871
+ } catch {
872
+ }
873
+ }
874
+ if (!this.entries.size) {
875
+ this.loaded = false;
876
+ return false;
877
+ }
878
+ return true;
879
+ }
880
+ get exists() {
881
+ return this.loaded;
882
+ }
883
+ get count() {
884
+ return this.entries.size;
885
+ }
886
+ /** A rescan is walking now. */
887
+ get busy() {
888
+ return !!this.running;
889
+ }
890
+ static same(a, item) {
891
+ return a.k === item.kind && (item.kind === "folder" || a.s === item.size && a.m === item.mtime && !!a.o === !!item.onlineOnly);
892
+ }
893
+ static snapOf(item, before) {
894
+ const keep = before && before.h && before.s === item.size && before.m === item.mtime ? { h: before.h } : {};
895
+ return { k: item.kind, s: item.size, m: item.mtime, ...keep, ...item.onlineOnly ? { o: true } : {} };
896
+ }
897
+ /** Keep a single change in step with the tree (the watcher and the ops call this). */
898
+ has(devicePath) {
899
+ return this.entries.has(devicePath);
900
+ }
901
+ /** What the snapshot knows of a path: kind, size, modified time; undefined when it does not. */
902
+ entry(devicePath) {
903
+ const e = this.entries.get(devicePath);
904
+ return e ? { kind: e.k, size: e.s, mtime: e.m } : void 0;
905
+ }
906
+ /** The names directly under the root, as the snapshot knows them (identity.looksLikeSharedFolder). */
907
+ topLevelNames() {
908
+ const names = [];
909
+ for (const key of this.entries.keys()) if (key.startsWith("/") && key.indexOf("/", 1) < 0) names.push(key.slice(1));
910
+ return names;
911
+ }
912
+ /** Whether this item is what the snapshot already knows (same kind; for a file the same size, time and placement). */
913
+ knows(item) {
914
+ const e = this.entries.get(item.externalId);
915
+ return !!e && _Snapshot.same(e, item);
916
+ }
917
+ set(item) {
918
+ this.entries.set(item.externalId, _Snapshot.snapOf(item, this.entries.get(item.externalId)));
919
+ this.touched?.set.add(item.externalId);
920
+ }
921
+ /** The cached hash of a file at this version; undefined when not computed or the file changed since. */
922
+ hashOf(devicePath, size, mtime) {
923
+ const e = this.entries.get(devicePath);
924
+ return e && e.h && e.s === size && e.m === mtime ? e.h : void 0;
925
+ }
926
+ setHash(devicePath, size, mtime, hash) {
927
+ const e = this.entries.get(devicePath);
928
+ if (e && e.s === size && e.m === mtime) e.h = hash;
929
+ else this.entries.set(devicePath, { k: "file", s: size, m: mtime, h: hash });
930
+ this.dirty = true;
931
+ }
932
+ dirty = false;
933
+ /** Persist when hashes were added since the last write (cheap to call after a batch). */
934
+ async persistIfDirty() {
935
+ if (!this.dirty) return;
936
+ this.dirty = false;
937
+ await this.persist();
938
+ }
939
+ /** Forget a path and everything under it (a folder the watcher saw go, whose children it never named). */
940
+ delete(devicePath) {
941
+ const was = this.entries.get(devicePath);
942
+ this.entries.delete(devicePath);
943
+ if (!was || was.k === "folder") {
944
+ const prefix = `${devicePath}/`;
945
+ for (const key of [...this.entries.keys()]) if (key.startsWith(prefix)) this.entries.delete(key);
946
+ }
947
+ this.touched?.removed.add(devicePath);
948
+ }
949
+ /**
950
+ * Forget one path, nothing under it: for the ops that already name every descendant (a folder move or trash
951
+ * reports each child), so ten thousand children cost ten thousand deletes, not ten thousand scans of the tree.
952
+ */
953
+ deleteOne(devicePath) {
954
+ this.entries.delete(devicePath);
955
+ this.touched?.removed.add(devicePath);
956
+ }
957
+ /** Whether an op or the watcher changed this path (or removed a folder above it) during the current walk. */
958
+ touchedDuringWalk(devicePath) {
959
+ if (!this.touched) return false;
960
+ if (this.touched.set.has(devicePath)) return true;
961
+ for (let p = devicePath; p; p = deviceDirname(p)) if (this.touched.removed.has(p)) return true;
962
+ return false;
963
+ }
964
+ /** One walk at a time per root: a rescan asked for while one runs gets that one's answer. */
965
+ rescan(rootPath, journal, options = {}) {
966
+ this.running ??= this.walk(rootPath, journal, options).finally(() => {
967
+ this.running = null;
968
+ });
969
+ return this.running;
970
+ }
971
+ /**
972
+ * Walk the tree; when a snapshot existed, journal every difference it can stand behind. Then the snapshot is
973
+ * the walk, plus what could not be read, plus what changed under it while it walked.
974
+ */
975
+ async walk(rootPath, journal, options) {
976
+ const there = () => import_fs7.default.existsSync(rootPath) && import_fs7.default.statSync(rootPath).isDirectory() && (options.stillThere?.() ?? true);
977
+ if (!there()) throw new Error(`${rootPath} is not available`);
978
+ await placeholdersFor(import_fs7.default.realpathSync(rootPath)).refresh();
979
+ const report = !!journal && this.loaded;
980
+ const seen = /* @__PURE__ */ new Map();
981
+ const upserts = [];
982
+ const unreadable = [];
983
+ const held = [];
984
+ let skipped = 0;
985
+ this.touched = { set: /* @__PURE__ */ new Set(), removed: /* @__PURE__ */ new Set() };
986
+ try {
987
+ for await (const item of walkAll(rootPath, "", { onUnreadable: (p) => unreadable.push(p), onFolder: options.onFolder, onSkipped: () => {
988
+ skipped += 1;
989
+ } })) {
990
+ const before = this.entries.get(item.externalId);
991
+ if (report && !before && item.kind === "file" && options.hold?.(item)) {
992
+ held.push(item.externalId);
993
+ continue;
994
+ }
995
+ seen.set(item.externalId, _Snapshot.snapOf(item, before));
996
+ if (!report) continue;
997
+ if (!before) upserts.push({ item, created: true });
998
+ else if (!_Snapshot.same(before, item)) upserts.push({ item, created: false });
999
+ }
1000
+ if (!there()) throw new Error(`${rootPath} is not available`);
1001
+ const under = (p) => unreadable.some((u) => u === "" || p === u || p.startsWith(`${u}/`));
1002
+ if (unreadable.length) {
1003
+ for (const [p, snap] of this.entries) if (!seen.has(p) && under(p)) seen.set(p, snap);
1004
+ }
1005
+ const gone = report ? [...this.entries.keys()].filter((p) => !seen.has(p) && !this.touchedDuringWalk(p)) : [];
1006
+ const markers = /* @__PURE__ */ new Map();
1007
+ const rootReal = import_fs7.default.realpathSync(rootPath);
1008
+ const unshared = new Set(gone.filter((p) => isIgnoredDevicePath(rootReal, p, markers)));
1009
+ const vanished = gone.filter((p) => !unshared.has(p));
1010
+ let refused;
1011
+ if (vanished.length && this.entries.size >= MASS_REMOVAL_MIN_ITEMS && vanished.length > this.entries.size * MASS_REMOVAL_SHARE && !this.takeAcceptance()) {
1012
+ refused = { removing: vanished.length, of: this.entries.size };
1013
+ for (const p of vanished) seen.set(p, this.entries.get(p));
1014
+ }
1015
+ const movedFrom = /* @__PURE__ */ new Map();
1016
+ if (report && gone.length && upserts.length) {
1017
+ const byShape = /* @__PURE__ */ new Map();
1018
+ for (const p of gone) {
1019
+ const e = this.entries.get(p);
1020
+ if (e?.k === "file") {
1021
+ const key = `${e.s}|${e.m}`;
1022
+ byShape.set(key, [...byShape.get(key) ?? [], p]);
1023
+ }
1024
+ }
1025
+ const claimed = /* @__PURE__ */ new Set();
1026
+ for (const u of upserts) {
1027
+ if (!u.created || u.item.kind !== "file") continue;
1028
+ const candidates = byShape.get(`${u.item.size}|${u.item.mtime}`) ?? [];
1029
+ if (candidates.length === 1 && !claimed.has(candidates[0])) {
1030
+ movedFrom.set(u.item.externalId, candidates[0]);
1031
+ claimed.add(candidates[0]);
1032
+ }
1033
+ }
1034
+ }
1035
+ let added = 0;
1036
+ let changed = 0;
1037
+ let removed = 0;
1038
+ let reset;
1039
+ if (journal && report && !refused && upserts.length + gone.length > journal.keepCount) {
1040
+ reset = { changes: upserts.length + gone.length };
1041
+ journal.reset();
1042
+ }
1043
+ if (journal && report && !reset) {
1044
+ for (const u of upserts) {
1045
+ if (this.touchedDuringWalk(u.item.externalId)) continue;
1046
+ const from = movedFrom.get(u.item.externalId);
1047
+ if (from) {
1048
+ changed += 1;
1049
+ journal.upsert(u.item, deviceDirname(from) !== deviceDirname(u.item.externalId), from);
1050
+ continue;
1051
+ }
1052
+ if (u.created) added += 1;
1053
+ else changed += 1;
1054
+ journal.upsert(u.item, u.created);
1055
+ }
1056
+ const paired = new Set(movedFrom.values());
1057
+ for (const p of (refused ? [...unshared] : gone).filter((g) => !paired.has(g)).sort((a, b) => b.length - a.length)) {
1058
+ removed += 1;
1059
+ journal.remove(p, { recoverable: !unshared.has(p) });
1060
+ }
1061
+ }
1062
+ if (this.touched.set.size || this.touched.removed.size) {
1063
+ for (const p of [...seen.keys()]) if (this.touchedDuringWalk(p) && !this.entries.has(p)) seen.delete(p);
1064
+ for (const p of this.touched.set) {
1065
+ const live = this.entries.get(p);
1066
+ if (live) seen.set(p, live);
1067
+ }
1068
+ }
1069
+ if (journal) await journal.flush();
1070
+ this.entries = seen;
1071
+ this.loaded = true;
1072
+ await this.persist();
1073
+ return { seen: seen.size, added, changed, removed, unreadable, held, skipped, ...refused ? { refused } : {}, ...reset ? { reset } : {} };
1074
+ } finally {
1075
+ this.touched = null;
1076
+ }
1077
+ }
1078
+ /** The person said a large removal is real (`tdai-device root accept-removals`): honoured once. */
1079
+ takeAcceptance() {
1080
+ try {
1081
+ import_fs7.default.unlinkSync(this.acceptFile);
1082
+ return true;
1083
+ } catch {
1084
+ return false;
1085
+ }
1086
+ }
1087
+ persisting = Promise.resolve();
1088
+ persistTimer = null;
1089
+ /**
1090
+ * Persist once the changes settle (PERSIST_SOON_MS after the last one): the watcher and the ops keep the snapshot in
1091
+ * memory, and a helper restarted before a rescan persisted it diffed the disk against a stale file and journaled
1092
+ * every change it had already reported (seen on both a laptop and a NAS as "~2 since last run" after a restart).
1093
+ */
1094
+ persistSoon(delayMs = PERSIST_SOON_MS) {
1095
+ if (this.persistTimer) clearTimeout(this.persistTimer);
1096
+ this.persistTimer = setTimeout(() => {
1097
+ this.persistTimer = null;
1098
+ void this.persist().catch(() => void 0);
1099
+ }, delayMs);
1100
+ this.persistTimer.unref?.();
1101
+ }
1102
+ /** A pending persistSoon, written now (a graceful stop). */
1103
+ async persistNow() {
1104
+ if (this.persistTimer) {
1105
+ clearTimeout(this.persistTimer);
1106
+ this.persistTimer = null;
1107
+ await this.persist().catch(() => void 0);
1108
+ }
1109
+ }
1110
+ /**
1111
+ * Write the snapshot: one writer at a time (a hash batch and a rescan both persist; two writers on one temp file
1112
+ * interleave garbage), synced to the disk BEFORE the rename (a power cut on a NAS otherwise keeps the rename and
1113
+ * loses the content: an empty file where the tree was), and a disk error is an error, not a hang.
1114
+ */
1115
+ persist() {
1116
+ const run = this.persisting.then(() => this.writeOut());
1117
+ this.persisting = run.catch(() => void 0);
1118
+ return run;
1119
+ }
1120
+ async writeOut() {
1121
+ import_fs7.default.mkdirSync(import_path7.default.dirname(this.file), { recursive: true });
1122
+ const tmp = `${this.file}.${process.pid}.tmp`;
1123
+ const handle = await import_fs7.default.promises.open(tmp, "w");
1124
+ try {
1125
+ let batch = [];
1126
+ let bytes = 0;
1127
+ for (const [p, snap] of this.entries) {
1128
+ const line = `${JSON.stringify({ p, ...snap })}
1129
+ `;
1130
+ batch.push(line);
1131
+ bytes += line.length;
1132
+ if (bytes >= 1024 * 1024) {
1133
+ await handle.writeFile(batch.join(""));
1134
+ batch = [];
1135
+ bytes = 0;
1136
+ }
1137
+ }
1138
+ if (batch.length) await handle.writeFile(batch.join(""));
1139
+ await handle.sync();
1140
+ } catch (error) {
1141
+ await handle.close().catch(() => void 0);
1142
+ await import_fs7.default.promises.rm(tmp, { force: true }).catch(() => void 0);
1143
+ throw error;
1144
+ }
1145
+ await handle.close();
1146
+ await import_fs7.default.promises.rename(tmp, this.file);
1147
+ }
1148
+ };
1149
+ function acceptRemovalsFile(dir) {
1150
+ return import_path7.default.join(dir, "accept-removals");
1151
+ }
1152
+
1153
+ // src/ops.ts
1154
+ var import_fs11 = __toESM(require("fs"));
1155
+ var import_path10 = __toESM(require("path"));
1156
+ var import_crypto3 = require("crypto");
1157
+
1158
+ // src/media.ts
1159
+ var import_path8 = __toESM(require("path"));
1160
+
1161
+ // src/exif.ts
1162
+ var import_fs8 = __toESM(require("fs"));
1163
+ var EMPTY = { takenAt: null, gpsLat: null, gpsLng: null, cameraMake: null, cameraModel: null, width: null, height: null };
1164
+ var HEAD_BYTES = 256 * 1024;
1165
+ function hasFacts(f) {
1166
+ return f.takenAt !== null || f.gpsLat !== null || f.cameraMake !== null || f.width !== null;
1167
+ }
1168
+ function exifTime(value) {
1169
+ if (!value) return null;
1170
+ const m = /^(\d{4}):(\d{2}):(\d{2})[ T](\d{2}):(\d{2}):(\d{2})/.exec(value.trim());
1171
+ if (!m) return null;
1172
+ const d = /* @__PURE__ */ new Date(`${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z`);
1173
+ return Number.isNaN(d.getTime()) || d.getUTCFullYear() < 1900 ? null : d.toISOString();
1174
+ }
1175
+ function u16(t, at) {
1176
+ return t.le ? t.buf.readUInt16LE(at) : t.buf.readUInt16BE(at);
1177
+ }
1178
+ function u32(t, at) {
1179
+ return t.le ? t.buf.readUInt32LE(at) : t.buf.readUInt32BE(at);
1180
+ }
1181
+ var TYPE_SIZE = { 1: 1, 2: 1, 3: 2, 4: 4, 5: 8, 7: 1, 9: 4, 10: 8 };
1182
+ function readIfd(t, offset) {
1183
+ const at = t.base + offset;
1184
+ if (at < 0 || at + 2 > t.buf.length) return null;
1185
+ const n = u16(t, at);
1186
+ if (n > 500 || at + 2 + n * 12 > t.buf.length) return null;
1187
+ const out = [];
1188
+ for (let i = 0; i < n; i += 1) {
1189
+ const e = at + 2 + i * 12;
1190
+ const type = u16(t, e + 2);
1191
+ const count = u32(t, e + 4);
1192
+ const size = (TYPE_SIZE[type] ?? 1) * count;
1193
+ const valueAt = size <= 4 ? e + 8 : t.base + u32(t, e + 8);
1194
+ out.push({ tag: u16(t, e), type, count, valueAt });
1195
+ }
1196
+ return out;
1197
+ }
1198
+ function ascii(t, e) {
1199
+ if (e.type !== 2 || e.valueAt < 0 || e.valueAt + e.count > t.buf.length) return null;
1200
+ const s = t.buf.toString("latin1", e.valueAt, e.valueAt + e.count).replace(/\0+$/, "").trim();
1201
+ return s || null;
1202
+ }
1203
+ function number(t, e) {
1204
+ if (e.valueAt < 0 || e.valueAt + 4 > t.buf.length) return null;
1205
+ if (e.type === 3) return u16(t, e.valueAt);
1206
+ if (e.type === 4) return u32(t, e.valueAt);
1207
+ return null;
1208
+ }
1209
+ function rationals(t, e) {
1210
+ if (e.type !== 5 || e.valueAt < 0 || e.valueAt + e.count * 8 > t.buf.length) return null;
1211
+ const out = [];
1212
+ for (let i = 0; i < e.count; i += 1) {
1213
+ const num2 = u32(t, e.valueAt + i * 8);
1214
+ const den = u32(t, e.valueAt + i * 8 + 4);
1215
+ out.push(den === 0 ? 0 : num2 / den);
1216
+ }
1217
+ return out;
1218
+ }
1219
+ function degrees(dms, ref) {
1220
+ if (!dms || dms.length < 3) return null;
1221
+ const value = dms[0] + dms[1] / 60 + dms[2] / 3600;
1222
+ if (!Number.isFinite(value)) return null;
1223
+ return ref === "S" || ref === "W" ? -value : value;
1224
+ }
1225
+ function factsFromTiff(buf, base) {
1226
+ if (base + 8 > buf.length) return EMPTY;
1227
+ const order = buf.toString("latin1", base, base + 2);
1228
+ if (order !== "II" && order !== "MM") return EMPTY;
1229
+ const t = { buf, base, le: order === "II" };
1230
+ if (u16(t, base + 2) !== 42) return EMPTY;
1231
+ const ifd0 = readIfd(t, u32(t, base + 4));
1232
+ if (!ifd0) return EMPTY;
1233
+ const facts = { ...EMPTY };
1234
+ let exifAt = null;
1235
+ let gpsAt = null;
1236
+ for (const e of ifd0) {
1237
+ if (e.tag === 271) facts.cameraMake = ascii(t, e)?.slice(0, 100) ?? null;
1238
+ else if (e.tag === 272) facts.cameraModel = ascii(t, e)?.slice(0, 100) ?? null;
1239
+ else if (e.tag === 34665) exifAt = number(t, e);
1240
+ else if (e.tag === 34853) gpsAt = number(t, e);
1241
+ else if (e.tag === 256) facts.width = number(t, e);
1242
+ else if (e.tag === 257) facts.height = number(t, e);
1243
+ }
1244
+ const exif = exifAt !== null ? readIfd(t, exifAt) : null;
1245
+ for (const e of exif ?? []) {
1246
+ if (e.tag === 36867 || e.tag === 36868 && !facts.takenAt) facts.takenAt = exifTime(ascii(t, e)) ?? facts.takenAt;
1247
+ else if (e.tag === 40962) facts.width = number(t, e) ?? facts.width;
1248
+ else if (e.tag === 40963) facts.height = number(t, e) ?? facts.height;
1249
+ }
1250
+ const gps = gpsAt !== null ? readIfd(t, gpsAt) : null;
1251
+ if (gps) {
1252
+ let latRef = null;
1253
+ let lngRef = null;
1254
+ let lat = null;
1255
+ let lng = null;
1256
+ for (const e of gps) {
1257
+ if (e.tag === 1) latRef = ascii(t, e);
1258
+ else if (e.tag === 2) lat = rationals(t, e);
1259
+ else if (e.tag === 3) lngRef = ascii(t, e);
1260
+ else if (e.tag === 4) lng = rationals(t, e);
1261
+ }
1262
+ const la = degrees(lat, latRef);
1263
+ const ln = degrees(lng, lngRef);
1264
+ if (la !== null && ln !== null && Math.abs(la) <= 90 && Math.abs(ln) <= 180 && (la !== 0 || ln !== 0)) {
1265
+ facts.gpsLat = la;
1266
+ facts.gpsLng = ln;
1267
+ }
1268
+ }
1269
+ return facts;
1270
+ }
1271
+ function factsFromBytes(buf) {
1272
+ if (buf.length >= 8 && (buf.toString("latin1", 0, 2) === "II" || buf.toString("latin1", 0, 2) === "MM")) return factsFromTiff(buf, 0);
1273
+ if (buf.length < 4 || buf[0] !== 255 || buf[1] !== 216) return EMPTY;
1274
+ let facts = { ...EMPTY };
1275
+ let at = 2;
1276
+ while (at + 4 <= buf.length && buf[at] === 255) {
1277
+ const marker = buf[at + 1];
1278
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
1279
+ at += 2;
1280
+ continue;
1281
+ }
1282
+ const len = buf.readUInt16BE(at + 2);
1283
+ if (marker === 225 && buf.toString("latin1", at + 4, at + 10) === "Exif\0\0") facts = { ...factsFromTiff(buf, at + 10), ...pick(facts, ["width", "height"]) };
1284
+ if (marker >= 192 && marker <= 195 || marker >= 197 && marker <= 199 || marker >= 201 && marker <= 203 || marker >= 205 && marker <= 207) {
1285
+ if (at + 9 <= buf.length) {
1286
+ facts.height = buf.readUInt16BE(at + 5);
1287
+ facts.width = buf.readUInt16BE(at + 7);
1288
+ }
1289
+ break;
1290
+ }
1291
+ if (marker === 218) break;
1292
+ at += 2 + len;
1293
+ }
1294
+ return facts;
1295
+ }
1296
+ function pick(f, keys) {
1297
+ const out = {};
1298
+ for (const k of keys) if (f[k] !== null) out[k] = f[k];
1299
+ return out;
1300
+ }
1301
+ async function factsFromFile(abs) {
1302
+ const fh = await import_fs8.default.promises.open(abs, "r");
1303
+ try {
1304
+ const buf = Buffer.alloc(HEAD_BYTES);
1305
+ const { bytesRead } = await fh.read(buf, 0, HEAD_BYTES, 0);
1306
+ return factsFromBytes(buf.subarray(0, bytesRead));
1307
+ } finally {
1308
+ await fh.close();
1309
+ }
1310
+ }
1311
+
1312
+ // src/media.ts
1313
+ var EXIF_EXTS = /* @__PURE__ */ new Set(["jpg", "jpeg", "tif", "tiff", "dng", "cr2", "nef", "arw"]);
1314
+ var MDLS_BATCH = 100;
1315
+ var MDLS_ATTRS = ["kMDItemContentCreationDate", "kMDItemLatitude", "kMDItemLongitude", "kMDItemAcquisitionMake", "kMDItemAcquisitionModel", "kMDItemPixelWidth", "kMDItemPixelHeight"];
1316
+ function num(raw) {
1317
+ const v = Number(raw.trim());
1318
+ return Number.isFinite(v) ? v : null;
1319
+ }
1320
+ function mdlsDate(raw) {
1321
+ const m = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) ([+-]\d{4})$/.exec(raw.trim());
1322
+ if (!m) return null;
1323
+ const d = /* @__PURE__ */ new Date(`${m[1]}T${m[2]}${m[3].slice(0, 3)}:${m[3].slice(3)}`);
1324
+ return Number.isNaN(d.getTime()) ? null : d.toISOString();
1325
+ }
1326
+ var UNKNOWN_FACTS = "unknown";
1327
+ async function factsFromSpotlight(absPaths) {
1328
+ const out = /* @__PURE__ */ new Map();
1329
+ for (let i = 0; i < absPaths.length; i += MDLS_BATCH) {
1330
+ const batch = absPaths.slice(i, i + MDLS_BATCH);
1331
+ const answered = await spotlightBatch(batch);
1332
+ if (answered) {
1333
+ for (const [p, f] of answered) out.set(p, f);
1334
+ continue;
1335
+ }
1336
+ if (batch.length === 1) {
1337
+ out.set(batch[0], UNKNOWN_FACTS);
1338
+ continue;
1339
+ }
1340
+ for (const p of batch) {
1341
+ const one = await spotlightBatch([p]);
1342
+ out.set(p, one ? one.get(p) ?? null : UNKNOWN_FACTS);
1343
+ }
1344
+ }
1345
+ return out;
1346
+ }
1347
+ async function spotlightBatch(batch) {
1348
+ let raw;
1349
+ try {
1350
+ raw = await runFile("/usr/bin/mdls", ["-raw", "-nullMarker", "(null)", ...MDLS_ATTRS.flatMap((a) => ["-name", a]), ...batch], { timeoutMs: 12e4 });
1351
+ } catch {
1352
+ return null;
1353
+ }
1354
+ const values = raw.split("\0");
1355
+ const expected = batch.length * MDLS_ATTRS.length;
1356
+ if (values.length < expected || values.length > expected + 1 || values.length === expected + 1 && values[expected].trim() !== "") return null;
1357
+ return parseSpotlight(batch, values);
1358
+ }
1359
+ function parseSpotlight(batch, values) {
1360
+ const out = /* @__PURE__ */ new Map();
1361
+ {
1362
+ batch.forEach((p, j) => {
1363
+ const v = (k) => values[j * MDLS_ATTRS.length + k] ?? "(null)";
1364
+ const at = (k) => v(k) === "(null)" ? null : v(k);
1365
+ const facts = {
1366
+ takenAt: at(0) ? mdlsDate(at(0)) : null,
1367
+ gpsLat: at(1) ? num(at(1)) : null,
1368
+ gpsLng: at(2) ? num(at(2)) : null,
1369
+ cameraMake: at(3)?.trim().slice(0, 100) ?? null,
1370
+ cameraModel: at(4)?.trim().slice(0, 100) ?? null,
1371
+ width: at(5) ? num(at(5)) : null,
1372
+ height: at(6) ? num(at(6)) : null
1373
+ };
1374
+ if (facts.gpsLat !== null && facts.gpsLng !== null && facts.gpsLat === 0 && facts.gpsLng === 0) {
1375
+ facts.gpsLat = null;
1376
+ facts.gpsLng = null;
1377
+ }
1378
+ out.set(p, hasFacts(facts) ? facts : null);
1379
+ });
1380
+ }
1381
+ return out;
1382
+ }
1383
+ async function readPhotoFacts(absPaths, platform = process.platform) {
1384
+ const out = /* @__PURE__ */ new Map();
1385
+ const remaining = [];
1386
+ if (platform === "darwin" && absPaths.length) {
1387
+ const known = await factsFromSpotlight(absPaths);
1388
+ for (const p of absPaths) {
1389
+ const f = known.get(p) ?? null;
1390
+ if (f && f !== UNKNOWN_FACTS) out.set(p, f);
1391
+ else remaining.push({ p, unknown: f === UNKNOWN_FACTS });
1392
+ }
1393
+ } else {
1394
+ remaining.push(...absPaths.map((p) => ({ p, unknown: false })));
1395
+ }
1396
+ for (const { p, unknown } of remaining) {
1397
+ if (!EXIF_EXTS.has(import_path8.default.extname(p).slice(1).toLowerCase())) {
1398
+ out.set(p, unknown ? UNKNOWN_FACTS : null);
1399
+ continue;
1400
+ }
1401
+ try {
1402
+ const f = await factsFromFile(p);
1403
+ out.set(p, hasFacts(f) ? f : null);
1404
+ } catch (error) {
1405
+ out.set(p, error.code === "ENOENT" ? UNKNOWN_FACTS : null);
1406
+ }
1407
+ }
1408
+ return out;
1409
+ }
1410
+
1411
+ // src/trash.ts
1412
+ var import_fs9 = __toESM(require("fs"));
1413
+ var import_os2 = __toESM(require("os"));
1414
+ var import_path9 = __toESM(require("path"));
1415
+ function rootHasTrash(root) {
1416
+ if (root.readOnly) return false;
1417
+ if (root.trash === "none") return false;
1418
+ if (root.trash === "dir") return !!root.trashDir && !trashHoldsRoot(root);
1419
+ if (root.trash === "share") return true;
1420
+ return process.env.TDAI_DOCKER !== "1" && (process.platform === "darwin" || process.platform === "linux" || process.platform === "win32");
1421
+ }
1422
+ async function uniqueIn(dir, name) {
1423
+ let candidate = import_path9.default.join(dir, name);
1424
+ if (!import_fs9.default.existsSync(candidate)) return candidate;
1425
+ const ext = import_path9.default.extname(name);
1426
+ const base = name.slice(0, name.length - ext.length);
1427
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
1428
+ candidate = import_path9.default.join(dir, `${base} ${stamp}${ext}`);
1429
+ for (let i = 2; import_fs9.default.existsSync(candidate); i += 1) candidate = import_path9.default.join(dir, `${base} ${stamp} (${i})${ext}`);
1430
+ return candidate;
1431
+ }
1432
+ async function moveAnywhere(from, to) {
1433
+ try {
1434
+ await import_fs9.default.promises.rename(from, to);
1435
+ } catch (error) {
1436
+ if (error.code !== "EXDEV") throw error;
1437
+ await import_fs9.default.promises.cp(from, to, { recursive: true, preserveTimestamps: true });
1438
+ await import_fs9.default.promises.rm(from, { recursive: true, force: true });
1439
+ }
1440
+ }
1441
+ function trashHoldsRoot(root) {
1442
+ const trash = import_path9.default.resolve(root.trashDir);
1443
+ const shared = import_path9.default.resolve(root.path);
1444
+ return shared === trash || shared.startsWith(trash + import_path9.default.sep);
1445
+ }
1446
+ function markTrashDir(root, options = {}) {
1447
+ if (root.readOnly || root.trash !== "dir" || !root.trashDir || trashHoldsRoot(root)) return;
1448
+ if (!options.create && !import_fs9.default.existsSync(root.trashDir)) return;
1449
+ import_fs9.default.mkdirSync(root.trashDir, { recursive: true });
1450
+ const marker = import_path9.default.join(root.trashDir, TRASH_MARKER);
1451
+ if (!import_fs9.default.existsSync(marker)) import_fs9.default.writeFileSync(marker, "The Drive AI helper puts deleted items here. Nothing in this folder is shared with the agent.\n");
1452
+ }
1453
+ async function trashToDir(trashDir, abs, relDir) {
1454
+ const dir = import_path9.default.join(trashDir, relDir);
1455
+ await import_fs9.default.promises.mkdir(dir, { recursive: true });
1456
+ await moveAnywhere(abs, await uniqueIn(dir, import_path9.default.basename(abs)));
1457
+ }
1458
+ async function stampAccess(abs) {
1459
+ const now = /* @__PURE__ */ new Date();
1460
+ const stack = [abs];
1461
+ while (stack.length) {
1462
+ const p = stack.pop();
1463
+ const s = await import_fs9.default.promises.lstat(p).catch(() => null);
1464
+ if (s?.isFile()) await import_fs9.default.promises.utimes(p, now, s.mtime).catch(() => void 0);
1465
+ else if (s?.isDirectory()) for (const name of await import_fs9.default.promises.readdir(p).catch(() => [])) stack.push(import_path9.default.join(p, name));
1466
+ }
1467
+ }
1468
+ async function trashToShareBin(root, abs) {
1469
+ const { bin, owner } = shareRecycleBin(root.path, abs);
1470
+ const dir = import_path9.default.join(bin, import_path9.default.relative(owner, import_path9.default.dirname(abs)));
1471
+ try {
1472
+ if (import_fs9.default.existsSync(bin)) import_fs9.default.accessSync(bin, import_fs9.default.constants.W_OK);
1473
+ await import_fs9.default.promises.mkdir(dir, { recursive: true });
1474
+ import_fs9.default.accessSync(dir, import_fs9.default.constants.W_OK);
1475
+ } catch (error) {
1476
+ const code = error.code;
1477
+ throw new TrashUnavailableError(`the recycle bin ${import_path9.default.basename(bin)} in ${import_path9.default.basename(owner)} cannot be written by this helper (${code ?? error.message}); move it instead`);
1478
+ }
1479
+ const target = await uniqueIn(dir, import_path9.default.basename(abs));
1480
+ await moveAnywhere(abs, target);
1481
+ await stampAccess(target).catch(() => void 0);
1482
+ }
1483
+ var TrashUnavailableError = class extends Error {
1484
+ constructor(message) {
1485
+ super(message);
1486
+ this.name = "TrashUnavailableError";
1487
+ }
1488
+ };
1489
+ function volumeTop(abs) {
1490
+ const dev = import_fs9.default.statSync(abs).dev;
1491
+ let top = import_path9.default.dirname(abs);
1492
+ for (; ; ) {
1493
+ const up = import_path9.default.dirname(top);
1494
+ if (up === top) return top;
1495
+ let upDev;
1496
+ try {
1497
+ upDev = import_fs9.default.statSync(up).dev;
1498
+ } catch {
1499
+ return top;
1500
+ }
1501
+ if (upDev !== dev) return top;
1502
+ top = up;
1503
+ }
1504
+ }
1505
+ async function trashFreedesktop(abs) {
1506
+ const home = process.env.XDG_DATA_HOME || import_path9.default.join(import_os2.default.homedir(), ".local", "share");
1507
+ const uid = typeof process.getuid === "function" ? process.getuid() : 0;
1508
+ const sameVolume = (a, b) => {
1509
+ try {
1510
+ return import_fs9.default.statSync(a).dev === import_fs9.default.statSync(b).dev;
1511
+ } catch {
1512
+ return false;
1513
+ }
1514
+ };
1515
+ const homeTrash = import_path9.default.join(home, "Trash");
1516
+ const candidates = sameVolume(abs, import_fs9.default.existsSync(homeTrash) ? homeTrash : home) ? [homeTrash] : [import_path9.default.join(volumeTop(abs), `.Trash-${uid}`)];
1517
+ const original = abs;
1518
+ let lastError = null;
1519
+ for (const trash of candidates) {
1520
+ const files = import_path9.default.join(trash, "files");
1521
+ const info = import_path9.default.join(trash, "info");
1522
+ try {
1523
+ await import_fs9.default.promises.mkdir(files, { recursive: true });
1524
+ await import_fs9.default.promises.mkdir(info, { recursive: true });
1525
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "");
1526
+ let target = import_path9.default.join(files, import_path9.default.basename(abs));
1527
+ for (let attempt = 0; ; attempt += 1) {
1528
+ target = attempt === 0 ? import_path9.default.join(files, import_path9.default.basename(abs)) : await uniqueIn(files, import_path9.default.basename(abs));
1529
+ try {
1530
+ await import_fs9.default.promises.writeFile(import_path9.default.join(info, `${import_path9.default.basename(target)}.trashinfo`), `[Trash Info]
1531
+ Path=${encodeURI(original)}
1532
+ DeletionDate=${stamp}
1533
+ `, { flag: "wx" });
1534
+ break;
1535
+ } catch (error) {
1536
+ if (error.code !== "EEXIST" || attempt > 20) throw error;
1537
+ }
1538
+ }
1539
+ try {
1540
+ await import_fs9.default.promises.rename(abs, target);
1541
+ } catch (error) {
1542
+ await import_fs9.default.promises.rm(import_path9.default.join(info, `${import_path9.default.basename(target)}.trashinfo`), { force: true }).catch(() => void 0);
1543
+ throw error;
1544
+ }
1545
+ return;
1546
+ } catch (error) {
1547
+ lastError = error;
1548
+ }
1549
+ }
1550
+ const code = lastError?.code;
1551
+ throw new TrashUnavailableError(`${import_path9.default.basename(abs)} is on a volume with no trash this helper can use (${code ?? lastError?.message ?? "unknown"}); move it instead`);
1552
+ }
1553
+ async function trashItem(root, abs, devicePath) {
1554
+ if (root.trash === "dir" && root.trashDir) {
1555
+ if (trashHoldsRoot(root)) throw new TrashUnavailableError(`the trash folder holds the shared folder; move it instead`);
1556
+ markTrashDir(root, { create: true });
1557
+ await trashToDir(root.trashDir, abs, import_path9.default.dirname(devicePath.slice(1)));
1558
+ return;
1559
+ }
1560
+ if (root.trash === "share") {
1561
+ await trashToShareBin(root, abs);
1562
+ return;
1563
+ }
1564
+ if (root.trash !== "os" || process.env.TDAI_DOCKER === "1") throw new Error("this folder has no trash");
1565
+ if (process.platform === "darwin") {
1566
+ await runFile("osascript", ["-e", "on run argv", "-e", 'tell application "Finder" to delete POSIX file (item 1 of argv)', "-e", "end run", abs]);
1567
+ return;
1568
+ }
1569
+ if (process.platform === "linux") {
1570
+ await trashFreedesktop(abs);
1571
+ return;
1572
+ }
1573
+ if (process.platform === "win32") {
1574
+ const isDir = import_fs9.default.statSync(abs).isDirectory();
1575
+ const method = isDir ? "DeleteDirectory" : "DeleteFile";
1576
+ await runPowerShell(`Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.FileIO.FileSystem]::${method}($env:TDAI_PS_PATH, 'OnlyErrorDialogs', 'SendToRecycleBin')`, { PATH: abs });
1577
+ return;
1578
+ }
1579
+ throw new Error(`no trash on ${process.platform}`);
1580
+ }
1581
+
1582
+ // src/provenance.ts
1583
+ var import_fs10 = __toESM(require("fs"));
1584
+ function quarantineValue(now = Date.now()) {
1585
+ return `0081;${Math.floor(now / 1e3).toString(16)};The Drive AI;`;
1586
+ }
1587
+ var ZONE_IDENTIFIER = "[ZoneTransfer]\r\nZoneId=3\r\n";
1588
+ async function markDownloaded(abs, platform = process.platform) {
1589
+ try {
1590
+ if (platform === "darwin") {
1591
+ await runFile("/usr/bin/xattr", ["-w", "com.apple.quarantine", quarantineValue(), abs], { timeoutMs: 5e3, maxBuffer: 64 * 1024 });
1592
+ } else if (platform === "win32") {
1593
+ await import_fs10.default.promises.writeFile(`${abs}:Zone.Identifier`, ZONE_IDENTIFIER);
1594
+ }
1595
+ } catch {
1596
+ }
1597
+ }
1598
+
1599
+ // src/ops.ts
1600
+ var OpError = class extends Error {
1601
+ constructor(code, message) {
1602
+ super(message);
1603
+ this.code = code;
1604
+ this.name = "OpError";
1605
+ }
1606
+ };
1607
+ function toOpError(error) {
1608
+ if (error instanceof OpError) return error;
1609
+ if (error instanceof PathError) return new OpError(error.code, error.message);
1610
+ if (error instanceof FolderDeniedError) return new OpError("UNAVAILABLE", `macOS has not allowed The Drive AI to read ${error.abs}`);
1611
+ if (error instanceof FolderUnreadableError) return new OpError("UNAVAILABLE", error.message);
1612
+ if (error instanceof TrashUnavailableError) return new OpError("NO_TRASH", error.message);
1613
+ const code = error.code;
1614
+ if (code === "ENOENT") return new OpError("NOT_FOUND", error.message);
1615
+ if (code === "EEXIST" || code === "ENOTEMPTY") return new OpError("EXISTS", error.message);
1616
+ if (code === "EACCES" || code === "EPERM" || code === "EROFS") return new OpError("PERMISSION_DENIED", error.message);
1617
+ return new OpError("INTERNAL", error.message ?? String(error));
1618
+ }
1619
+ var MAX_WRITE_BYTES = 64 * 1024 * 1024;
1620
+ var CLOSED_MEMORY_MS = 5 * 6e4;
1621
+ var CLOSED_MEMORY_MAX = 2e3;
1622
+ var TEMP_MARK = ".tdai-";
1623
+ function tempPathFor(destinationAbs, stream) {
1624
+ return import_path10.default.join(import_path10.default.dirname(destinationAbs), `.${import_path10.default.basename(destinationAbs)}${TEMP_MARK}${process.pid}-${stream}.tmp`);
1625
+ }
1626
+ var TEMP_STALE_MS = 60 * 6e4;
1627
+ function pidAlive(pid) {
1628
+ try {
1629
+ process.kill(pid, 0);
1630
+ return true;
1631
+ } catch (error) {
1632
+ return error.code === "EPERM";
1633
+ }
1634
+ }
1635
+ async function sweepTempFiles(folderAbs2) {
1636
+ let removed = 0;
1637
+ let names;
1638
+ try {
1639
+ names = await import_fs11.default.promises.readdir(folderAbs2);
1640
+ } catch {
1641
+ return 0;
1642
+ }
1643
+ for (const name of names) {
1644
+ const at = name.indexOf(TEMP_MARK);
1645
+ if (!name.startsWith(".") || at < 0 || !name.endsWith(".tmp")) continue;
1646
+ const tail = name.slice(at + TEMP_MARK.length);
1647
+ const pid = Number(tail.slice(0, tail.indexOf("-")));
1648
+ const abs = import_path10.default.join(folderAbs2, name);
1649
+ const stat = statOrNull(abs);
1650
+ if (!stat || !stat.isFile()) continue;
1651
+ const stale = Date.now() - stat.mtimeMs > TEMP_STALE_MS;
1652
+ const orphan = Number.isFinite(pid) && pid !== process.pid && !pidAlive(pid);
1653
+ if (!stale && !orphan) continue;
1654
+ try {
1655
+ await import_fs11.default.promises.rm(abs, { force: true });
1656
+ removed += 1;
1657
+ } catch {
1658
+ }
1659
+ }
1660
+ return removed;
1661
+ }
1662
+ async function landTempFile(tmp, destination, mode) {
1663
+ if (mode === "replace" || process.platform === "win32") {
1664
+ if (mode === "create" && import_fs11.default.existsSync(destination)) throw new OpError("EXISTS", `${import_path10.default.basename(destination)} exists`);
1665
+ try {
1666
+ await import_fs11.default.promises.rename(tmp, destination);
1667
+ } catch (error) {
1668
+ if (error.code === "EPERM" && process.platform === "win32") throw new OpError("PERMISSION_DENIED", `${import_path10.default.basename(destination)} is open in another program; close it and try again`);
1669
+ throw error;
1670
+ }
1671
+ return;
1672
+ }
1673
+ try {
1674
+ await import_fs11.default.promises.link(tmp, destination);
1675
+ } catch (error) {
1676
+ const code = error.code;
1677
+ if (code === "EEXIST") throw new OpError("EXISTS", `${import_path10.default.basename(destination)} exists`);
1678
+ if (code !== "EPERM" && code !== "ENOTSUP" && code !== "EXDEV" && code !== "EMLINK") throw error;
1679
+ if (import_fs11.default.existsSync(destination)) throw new OpError("EXISTS", `${import_path10.default.basename(destination)} exists`);
1680
+ await import_fs11.default.promises.rename(tmp, destination);
1681
+ return;
1682
+ }
1683
+ await import_fs11.default.promises.rm(tmp, { force: true }).catch(() => void 0);
1684
+ }
1685
+ var HASH_BATCH = 200;
1686
+ var CREATE_STABLE_MS = 3e3;
1687
+ var RECENT_WRITE_MS = 6e4;
1688
+ function sha256File(abs) {
1689
+ return new Promise((resolve, reject) => {
1690
+ const hash = (0, import_crypto3.createHash)("sha256");
1691
+ const stream = import_fs11.default.createReadStream(abs, { highWaterMark: 1024 * 1024 });
1692
+ stream.on("data", (chunk) => hash.update(chunk));
1693
+ stream.on("error", reject);
1694
+ stream.on("end", () => resolve(hash.digest("hex")));
1695
+ });
1696
+ }
1697
+ function rootStateReason(state, label) {
1698
+ if (state === "denied") return `macOS has not allowed The Drive AI to read "${label}". Allow it under System Settings \u2192 Privacy & Security \u2192 Files and Folders, then reopen the app.`;
1699
+ if (state === "missing") return `"${label}" is not available on this computer right now (a disk unplugged, a network drive asleep). It resumes when it is back.`;
1700
+ return null;
1701
+ }
1702
+ var MOVE_PAIR_MS = 2500;
1703
+ var RootOps = class {
1704
+ constructor(root) {
1705
+ this.root = root;
1706
+ }
1707
+ /** New files seen once, waiting to be seen again unchanged before they are reported created. */
1708
+ settling = /* @__PURE__ */ new Map();
1709
+ /**
1710
+ * Files the watcher saw vanish, held for MOVE_PAIR_MS: a rename or a move inside the root arrives as an unlink and
1711
+ * an add, and the add of a file with the vanished one's size and time IS the vanished one, moved. Reported as such;
1712
+ * otherwise the removal goes out when the wait ends.
1713
+ */
1714
+ departing = /* @__PURE__ */ new Map();
1715
+ get rootPath() {
1716
+ return this.root.config.path;
1717
+ }
1718
+ /** The journal's position, as the nudge to the server carries it. */
1719
+ get position() {
1720
+ return this.root.journal.position;
1721
+ }
1722
+ /** Whether the snapshot knows this path (the watcher asks before walking a folder's subtree). */
1723
+ knows(devicePath) {
1724
+ return this.root.snapshot.has(normalizeDevicePath(devicePath));
1725
+ }
1726
+ /** Whether the folder at the root's path is the one that was shared (not merely a folder of that name). */
1727
+ present() {
1728
+ return this.root.identity ? this.root.identity.check(this.rootPath) === "ok" : import_fs11.default.existsSync(this.rootPath);
1729
+ }
1730
+ /** The root went away (a volume unmounted, another folder in its place): paused, never emptied. */
1731
+ lost() {
1732
+ if (this.root.state !== "missing") {
1733
+ this.root.state = "missing";
1734
+ this.root.onStateChange?.("missing");
1735
+ }
1736
+ return new OpError("UNAVAILABLE", rootStateReason("missing", this.root.config.label));
1737
+ }
1738
+ /** Every op starts here: a root that is missing or denied answers UNAVAILABLE, never a half answer. */
1739
+ available() {
1740
+ if (this.root.state && this.root.state !== "ok") throw new OpError("UNAVAILABLE", rootStateReason(this.root.state, this.root.config.label) ?? "the folder is not available");
1741
+ if (!this.present()) throw this.lost();
1742
+ }
1743
+ /** A write answers once what it journaled is on disk. */
1744
+ async landed(result) {
1745
+ await this.root.journal.flush();
1746
+ return result;
1747
+ }
1748
+ writable() {
1749
+ if (this.root.config.readOnly) throw new OpError("READ_ONLY", `${this.root.config.label} is shared read-only`);
1750
+ }
1751
+ /**
1752
+ * `created` when the path was not known before: the snapshot says, so a new file is told apart from a rewrite.
1753
+ * `movedFrom`: the item stood there a moment ago (an op's move, a watcher's unlink+add pair, a rescan's match):
1754
+ * ONE journal entry, so the server keeps the node — its id, its text, the datasets that name it — instead of
1755
+ * burying one and birthing another. A move into another folder still counts as created there (a file LANDED,
1756
+ * which is what a "when a file lands in Inbox" trigger means); a rename inside its folder does not.
1757
+ */
1758
+ record(item, options = {}) {
1759
+ const movedFrom = options.movedFrom && options.movedFrom !== item.externalId ? options.movedFrom : void 0;
1760
+ const created = movedFrom ? deviceDirname(movedFrom) !== deviceDirname(item.externalId) : !this.root.snapshot.has(item.externalId);
1761
+ const sent = this.withHash(item);
1762
+ this.root.journal.upsert(sent, created, movedFrom);
1763
+ if (movedFrom) this.root.snapshot.deleteOne(movedFrom);
1764
+ this.root.snapshot.set(sent);
1765
+ this.root.snapshot.persistSoon();
1766
+ }
1767
+ forget(devicePath) {
1768
+ this.root.journal.remove(devicePath);
1769
+ this.root.snapshot.delete(devicePath);
1770
+ this.root.snapshot.persistSoon();
1771
+ }
1772
+ /** Descendants a folder op already walked: each forgotten on its own, deepest first (no scan of the tree per child). */
1773
+ forgetWalked(children) {
1774
+ for (const p of children.sort((a, b) => b.length - a.length)) {
1775
+ this.root.journal.remove(p);
1776
+ this.root.snapshot.deleteOne(p);
1777
+ }
1778
+ }
1779
+ /**
1780
+ * An item as it leaves the helper: a file carries its SHA-256 when the helper has computed it for this very
1781
+ * version (the snapshot's cache), as `sha256:<hex>`, the key the server stores. The server compares what the
1782
+ * catalogue holds with what the helper reports to decide whether a file changed, so the two must agree.
1783
+ */
1784
+ withHash(item) {
1785
+ if (!item || item.kind !== "file") return item;
1786
+ const h = this.root.snapshot.hashOf(item.externalId, item.size, item.mtime);
1787
+ const rootReal = import_fs11.default.realpathSync(this.rootPath);
1788
+ const online = item.onlineOnly || placeholdersFor(rootReal).has(import_path10.default.join(rootReal, ...item.externalId.split("/").filter(Boolean)));
1789
+ return { ...item, ...h ? { contentHash: `sha256:${h}` } : {}, ...online ? { onlineOnly: true } : {} };
1790
+ }
1791
+ itemAt(resolved) {
1792
+ const stat = statOrNull(resolved.abs);
1793
+ if (!stat) throw new OpError("NOT_FOUND", `no such item: ${resolved.device || "/"}`);
1794
+ const item = itemFor(resolved.device, stat, resolved.device === "" ? this.root.config.label : void 0);
1795
+ if (!item) throw new OpError("NOT_FOUND", `${resolved.device} is not a file or folder`);
1796
+ return item;
1797
+ }
1798
+ async stat(params) {
1799
+ this.available();
1800
+ try {
1801
+ return this.withHash(this.itemAt(resolveUnder(this.rootPath, params.path, { mustExist: true })));
1802
+ } catch (error) {
1803
+ if (toOpError(error).code === "NOT_FOUND") return null;
1804
+ throw toOpError(error);
1805
+ }
1806
+ }
1807
+ async list(params) {
1808
+ this.available();
1809
+ const resolved = resolveUnder(this.rootPath, params.path, { mustExist: true });
1810
+ return listPage(this.rootPath, resolved.device, params.cursor, Math.max(1, Math.min(params.limit || 200, 5e3)), { map: (i) => this.withHash(i) });
1811
+ }
1812
+ async enumerate(params) {
1813
+ this.available();
1814
+ return walkPage(this.rootPath, params.cursor, Math.max(1, Math.min(params.limit || 2e3, 1e4)), { map: (i) => this.withHash(i) });
1815
+ }
1816
+ async changes(params) {
1817
+ this.available();
1818
+ return this.root.journal.since(params.cursor, Math.max(1, Math.min(params.limit || 2e3, 1e4)));
1819
+ }
1820
+ async mkdir(params) {
1821
+ this.available();
1822
+ this.writable();
1823
+ const resolved = resolveUnder(this.rootPath, params.path);
1824
+ if (resolved.device === "") throw new OpError("EXISTS", "the root exists");
1825
+ if (import_fs11.default.existsSync(resolved.abs)) throw new OpError("EXISTS", `${resolved.device} exists`);
1826
+ try {
1827
+ await import_fs11.default.promises.mkdir(resolved.abs);
1828
+ } catch (error) {
1829
+ throw toOpError(error);
1830
+ }
1831
+ const item = this.itemAt(resolved);
1832
+ this.record(item);
1833
+ return this.landed(item);
1834
+ }
1835
+ /** `to` is the full destination path: one call renames or moves, like Dropbox's move_v2. Descendants are reported. */
1836
+ async move(params) {
1837
+ this.available();
1838
+ this.writable();
1839
+ const from = resolveUnder(this.rootPath, params.from, { mustExist: true });
1840
+ const to = resolveUnder(this.rootPath, params.to);
1841
+ if (from.device === "" || to.device === "") throw new OpError("BAD_PATH", "the root cannot be moved");
1842
+ if (to.device === from.device) return this.itemAt(from);
1843
+ if (to.device.startsWith(`${from.device}/`)) throw new OpError("BAD_PATH", "a folder cannot be moved into itself");
1844
+ if (import_fs11.default.existsSync(to.abs) && !sameEntry(from, to)) throw new OpError("EXISTS", `${to.device} exists`);
1845
+ const wasFolder = statOrNull(from.abs)?.isDirectory() ?? false;
1846
+ const oldChildren = [];
1847
+ if (wasFolder) for await (const child of walkAll(this.rootPath, from.device)) oldChildren.push(child.externalId);
1848
+ try {
1849
+ await import_fs11.default.promises.rename(from.abs, to.abs);
1850
+ } catch (error) {
1851
+ if (error.code !== "EXDEV") throw toOpError(error);
1852
+ try {
1853
+ await import_fs11.default.promises.cp(from.abs, to.abs, { recursive: true, preserveTimestamps: true, errorOnExist: true, force: false });
1854
+ } catch (copyError) {
1855
+ await import_fs11.default.promises.rm(to.abs, { recursive: true, force: true }).catch(() => void 0);
1856
+ throw toOpError(copyError);
1857
+ }
1858
+ try {
1859
+ await import_fs11.default.promises.rm(from.abs, { recursive: true, force: true });
1860
+ } catch (rmError) {
1861
+ throw toOpError(rmError);
1862
+ }
1863
+ }
1864
+ const landed = this.itemAt(to);
1865
+ for (const p of oldChildren) this.root.snapshot.deleteOne(p);
1866
+ this.record(landed, { movedFrom: from.device });
1867
+ if (wasFolder) for await (const child of walkAll(this.rootPath, to.device)) this.record(child, { movedFrom: `${from.device}${child.externalId.slice(to.device.length)}` });
1868
+ return this.landed(landed);
1869
+ }
1870
+ async copy(params) {
1871
+ this.available();
1872
+ this.writable();
1873
+ const from = resolveUnder(this.rootPath, params.from, { mustExist: true });
1874
+ const to = resolveUnder(this.rootPath, params.to);
1875
+ if (from.device === "" || to.device === "") throw new OpError("BAD_PATH", "the root cannot be copied");
1876
+ if (import_fs11.default.existsSync(to.abs)) throw new OpError("EXISTS", `${to.device} exists`);
1877
+ if (to.device.startsWith(`${from.device}/`)) throw new OpError("BAD_PATH", "a folder cannot be copied into itself");
1878
+ try {
1879
+ await import_fs11.default.promises.cp(from.abs, to.abs, { recursive: true, preserveTimestamps: true });
1880
+ } catch (error) {
1881
+ throw toOpError(error);
1882
+ }
1883
+ if (statOrNull(to.abs)?.isDirectory()) {
1884
+ for await (const child of walkAll(this.rootPath, to.device)) if (child.kind === "file") await markDownloaded(resolveUnder(this.rootPath, child.externalId).abs);
1885
+ } else {
1886
+ await markDownloaded(to.abs);
1887
+ }
1888
+ const landed = this.itemAt(to);
1889
+ this.record(landed);
1890
+ if (landed.kind === "folder") for await (const child of walkAll(this.rootPath, to.device)) this.record(child);
1891
+ return this.landed(landed);
1892
+ }
1893
+ async trash(params) {
1894
+ this.available();
1895
+ this.writable();
1896
+ if (!rootHasTrash(this.root.config)) throw new OpError("NO_TRASH", `${this.root.config.label} has no trash; move the item instead`);
1897
+ const target = resolveUnder(this.rootPath, params.path, { mustExist: true });
1898
+ if (target.device === "") throw new OpError("BAD_PATH", "the root cannot be trashed");
1899
+ const children = [];
1900
+ if (statOrNull(target.abs)?.isDirectory()) for await (const child of walkAll(this.rootPath, target.device)) children.push(child.externalId);
1901
+ try {
1902
+ await trashItem(this.root.config, target.abs, target.device);
1903
+ } catch (error) {
1904
+ throw toOpError(error);
1905
+ }
1906
+ this.forgetWalked(children);
1907
+ this.forget(target.device);
1908
+ return this.landed({ ok: true });
1909
+ }
1910
+ async write(params) {
1911
+ this.available();
1912
+ this.writable();
1913
+ const data = Buffer.isBuffer(params.data) ? params.data : Buffer.from(params.data);
1914
+ if (data.length > MAX_WRITE_BYTES) throw new OpError("TOO_LARGE", `${data.length} bytes is more than the helper accepts in one write (${MAX_WRITE_BYTES})`);
1915
+ const resolved = resolveUnder(this.rootPath, params.path);
1916
+ if (resolved.device === "") throw new OpError("BAD_PATH", "the root is a folder");
1917
+ const exists = import_fs11.default.existsSync(resolved.abs);
1918
+ if (params.mode === "create" && exists) throw new OpError("EXISTS", `${resolved.device} exists`);
1919
+ if (params.mode === "replace" && !exists) throw new OpError("NOT_FOUND", `no such file: ${resolved.device}`);
1920
+ if (exists && statOrNull(resolved.abs)?.isDirectory()) throw new OpError("EXISTS", `${resolved.device} is a folder`);
1921
+ const tmp = tempPathFor(resolved.abs, `w${Date.now().toString(36)}`);
1922
+ try {
1923
+ await import_fs11.default.promises.writeFile(tmp, data, { flag: "wx" });
1924
+ await markDownloaded(tmp);
1925
+ await landTempFile(tmp, resolved.abs, params.mode);
1926
+ } catch (error) {
1927
+ await import_fs11.default.promises.rm(tmp, { force: true }).catch(() => void 0);
1928
+ throw toOpError(error);
1929
+ }
1930
+ const item = this.itemAt(resolved);
1931
+ this.record(item);
1932
+ return this.landed(item);
1933
+ }
1934
+ // ── Streamed writes ──────────────────────────────────────────────────
1935
+ /** Writes in progress, by the stream the server named: a temp file beside the destination, filled chunk by chunk. */
1936
+ writes = /* @__PURE__ */ new Map();
1937
+ /** Closes that completed, by stream, for a few minutes: a close re-asked after the helper's memory of the request lapsed answers from here, never from whatever sits at the path. */
1938
+ closed = /* @__PURE__ */ new Map();
1939
+ /** Streams open for writing, for the host to abort when the line goes. */
1940
+ get openWrites() {
1941
+ return [...this.writes.keys()];
1942
+ }
1943
+ /** Every write still open is dropped (a graceful stop): its temp file goes with it. */
1944
+ async abortAllWrites() {
1945
+ for (const stream of [...this.writes.keys()]) await this.abortWrite(stream);
1946
+ }
1947
+ /**
1948
+ * Open a streamed write (the mirror of openRead): the same checks as `write`, then a temp file beside the
1949
+ * destination that the chunks fill. Nothing appears under the name until closeWrite renames it over.
1950
+ */
1951
+ async openWrite(params) {
1952
+ this.available();
1953
+ this.writable();
1954
+ if (typeof params.stream !== "string" || !params.stream) throw new OpError("BAD_PATH", "a write stream needs a name");
1955
+ if (this.writes.has(params.stream)) return { stream: params.stream };
1956
+ const resolved = resolveUnder(this.rootPath, params.path);
1957
+ if (resolved.device === "") throw new OpError("BAD_PATH", "the root is a folder");
1958
+ const exists = import_fs11.default.existsSync(resolved.abs);
1959
+ if (params.mode === "create" && exists) throw new OpError("EXISTS", `${resolved.device} exists`);
1960
+ if (params.mode === "replace" && !exists) throw new OpError("NOT_FOUND", `no such file: ${resolved.device}`);
1961
+ if (exists && statOrNull(resolved.abs)?.isDirectory()) throw new OpError("EXISTS", `${resolved.device} is a folder`);
1962
+ const tmp = tempPathFor(resolved.abs, params.stream);
1963
+ let handle;
1964
+ try {
1965
+ handle = await import_fs11.default.promises.open(tmp, "wx");
1966
+ } catch (error) {
1967
+ throw toOpError(error);
1968
+ }
1969
+ const expected = typeof params.size === "number" && Number.isFinite(params.size) && params.size >= 0 ? params.size : null;
1970
+ this.writes.set(params.stream, { resolved, tmp, handle, mode: params.mode, expected, seq: 0, bytes: 0 });
1971
+ return { stream: params.stream };
1972
+ }
1973
+ /** One chunk, in order, onto the temp file; true once it is written (the server's permission to send the next). */
1974
+ async appendWrite(chunk) {
1975
+ const open = this.writes.get(chunk.stream);
1976
+ if (!open) return false;
1977
+ if (chunk.seq !== open.seq) {
1978
+ await this.abortWrite(chunk.stream);
1979
+ return false;
1980
+ }
1981
+ const data = Buffer.isBuffer(chunk.data) ? chunk.data : Buffer.from(chunk.data);
1982
+ try {
1983
+ await open.handle.write(data);
1984
+ } catch (error) {
1985
+ await this.abortWrite(chunk.stream);
1986
+ throw toOpError(error);
1987
+ }
1988
+ open.seq += 1;
1989
+ open.bytes += data.length;
1990
+ return true;
1991
+ }
1992
+ /** The write is complete: synced, renamed over the destination, journaled. The item as it now is. */
1993
+ async closeWrite(params) {
1994
+ const open = this.writes.get(params.stream);
1995
+ if (!open) {
1996
+ const done = this.closed.get(params.stream);
1997
+ if (done && Date.now() - done.at < CLOSED_MEMORY_MS) return done.item;
1998
+ throw new OpError("NOT_FOUND", `no write stream ${params.stream}`);
1999
+ }
2000
+ if (normalizeDevicePath(params.path) !== open.resolved.device) {
2001
+ await this.abortWrite(params.stream);
2002
+ throw new OpError("BAD_PATH", "the close names another path than the open");
2003
+ }
2004
+ this.writes.delete(params.stream);
2005
+ try {
2006
+ if (open.expected !== null && open.bytes !== open.expected) throw new OpError("INTERNAL", `the write ended at ${open.bytes} bytes, not the ${open.expected} announced`);
2007
+ if (typeof params.bytes === "number" && params.bytes !== open.bytes) throw new OpError("INTERNAL", `the server sent ${params.bytes} bytes, this disk took ${open.bytes}`);
2008
+ try {
2009
+ await open.handle.sync();
2010
+ } catch (error) {
2011
+ const code = error.code;
2012
+ if (code !== "EINVAL" && code !== "ENOTSUP") throw error;
2013
+ }
2014
+ await open.handle.close();
2015
+ await markDownloaded(open.tmp);
2016
+ await landTempFile(open.tmp, open.resolved.abs, open.mode);
2017
+ } catch (error) {
2018
+ await open.handle.close().catch(() => void 0);
2019
+ await import_fs11.default.promises.rm(open.tmp, { force: true }).catch(() => void 0);
2020
+ throw error instanceof OpError ? error : toOpError(error);
2021
+ }
2022
+ const item = this.itemAt(open.resolved);
2023
+ this.record(item);
2024
+ const landed = this.landed(item);
2025
+ this.closed.set(params.stream, { at: Date.now(), item });
2026
+ for (const [stream, entry] of this.closed) {
2027
+ if (Date.now() - entry.at >= CLOSED_MEMORY_MS || this.closed.size > CLOSED_MEMORY_MAX) this.closed.delete(stream);
2028
+ else break;
2029
+ }
2030
+ return landed;
2031
+ }
2032
+ /** The server gave up (or the line went): what was written so far is dropped; the destination is untouched. */
2033
+ async abortWrite(stream) {
2034
+ const open = this.writes.get(stream);
2035
+ if (!open) return;
2036
+ this.writes.delete(stream);
2037
+ await open.handle.close().catch(() => void 0);
2038
+ await import_fs11.default.promises.rm(open.tmp, { force: true }).catch(() => void 0);
2039
+ }
2040
+ /**
2041
+ * SHA-256 of each named file, computed here where the bytes are (DEVICE_MOUNTS.md §4): nothing crosses the
2042
+ * network but the digests. A cached digest for the same version is answered without reading the file. A file
2043
+ * that is gone, unreadable, a folder or over `maxBytes` answers null. At most HASH_BATCH paths per call.
2044
+ */
2045
+ async hash(params) {
2046
+ this.available();
2047
+ const hashes = {};
2048
+ for (const raw of (params.paths ?? []).slice(0, HASH_BATCH)) {
2049
+ let resolved;
2050
+ try {
2051
+ resolved = resolveUnder(this.rootPath, raw, { mustExist: true });
2052
+ } catch {
2053
+ hashes[raw] = null;
2054
+ continue;
2055
+ }
2056
+ const stat = statOrNull(resolved.abs);
2057
+ if (!stat || !stat.isFile() || typeof params.maxBytes === "number" && stat.size > params.maxBytes) {
2058
+ hashes[raw] = null;
2059
+ continue;
2060
+ }
2061
+ if (placeholdersFor(import_fs11.default.realpathSync(this.rootPath)).has(resolved.abs)) {
2062
+ hashes[raw] = null;
2063
+ continue;
2064
+ }
2065
+ const mtime = stat.mtime.toISOString();
2066
+ const cached = this.root.snapshot.hashOf(resolved.device, stat.size, mtime);
2067
+ if (cached) {
2068
+ hashes[raw] = `sha256:${cached}`;
2069
+ continue;
2070
+ }
2071
+ try {
2072
+ const digest = await sha256File(resolved.abs);
2073
+ this.root.snapshot.setHash(resolved.device, stat.size, mtime, digest);
2074
+ hashes[raw] = `sha256:${digest}`;
2075
+ } catch {
2076
+ hashes[raw] = null;
2077
+ }
2078
+ }
2079
+ await this.root.journal.flush();
2080
+ await this.root.snapshot.persistIfDirty().catch(() => void 0);
2081
+ return { hashes };
2082
+ }
2083
+ /**
2084
+ * Photo facts for these files, read here (media.ts): Spotlight on a Mac, the EXIF reader elsewhere. A placeholder
2085
+ * is answered without being fetched (Spotlight knows it; the reader does not open it). Every path is answered.
2086
+ */
2087
+ async media(params) {
2088
+ this.available();
2089
+ const rootReal = import_fs11.default.realpathSync(this.rootPath);
2090
+ const byAbs = /* @__PURE__ */ new Map();
2091
+ const media = {};
2092
+ for (const raw of (params.paths ?? []).slice(0, HASH_BATCH)) {
2093
+ let resolved;
2094
+ try {
2095
+ resolved = resolveUnder(this.rootPath, raw, { mustExist: true });
2096
+ } catch {
2097
+ media[raw] = null;
2098
+ continue;
2099
+ }
2100
+ const stat = statOrNull(resolved.abs);
2101
+ if (!stat || !stat.isFile()) {
2102
+ media[raw] = null;
2103
+ continue;
2104
+ }
2105
+ byAbs.set(resolved.abs, raw);
2106
+ }
2107
+ const toRead = [...byAbs.keys()].filter((abs) => process.platform === "darwin" || !placeholdersFor(rootReal).has(abs));
2108
+ for (const abs of byAbs.keys()) if (!toRead.includes(abs)) media[byAbs.get(abs)] = null;
2109
+ const facts = await readPhotoFacts(toRead);
2110
+ for (const [abs, raw] of byAbs) if (toRead.includes(abs)) media[raw] = facts.get(abs) ?? null;
2111
+ return { media };
2112
+ }
2113
+ /** Open a file for streaming: the stream itself is driven by the client (chunks with acks). */
2114
+ openRead(params) {
2115
+ this.available();
2116
+ const resolved = resolveUnder(this.rootPath, params.path, { mustExist: true });
2117
+ const stat = statOrNull(resolved.abs);
2118
+ if (!stat || !stat.isFile()) throw new OpError("NOT_FOUND", `no such file: ${resolved.device}`);
2119
+ if (!params.allowFetch && placeholdersFor(import_fs11.default.realpathSync(this.rootPath)).has(resolved.abs)) throw new OpError("ONLINE_ONLY", `${deviceBasename(resolved.device)} is online-only (its bytes are in the cloud, not on this computer); reading it would download it`);
2120
+ if (typeof params.maxBytes === "number" && params.maxBytes > 0 && stat.size > params.maxBytes) throw new OpError("TOO_LARGE", `${deviceBasename(resolved.device)} is ${stat.size} bytes; the limit for this read is ${params.maxBytes}`);
2121
+ return { abs: resolved.abs, size: stat.size, name: deviceBasename(resolved.device) };
2122
+ }
2123
+ /**
2124
+ * The watcher's report of a path that may have changed: stat it and journal the difference, if there is one.
2125
+ * A new file is reported created only when a second look, CREATE_STABLE_MS later, finds the same size and time.
2126
+ */
2127
+ async observe(devicePath) {
2128
+ const device = normalizeDevicePath(devicePath);
2129
+ if (device === "") return;
2130
+ if (!this.present()) {
2131
+ this.lost();
2132
+ return;
2133
+ }
2134
+ let resolved;
2135
+ try {
2136
+ resolved = resolveUnder(this.rootPath, device);
2137
+ } catch {
2138
+ return;
2139
+ }
2140
+ const stat = statOrNull(resolved.abs);
2141
+ let item = stat ? itemFor(device, stat) : null;
2142
+ if (item?.kind === "file" && await placeholdersFor(import_fs11.default.realpathSync(this.rootPath)).check(resolved.abs)) item = { ...item, onlineOnly: true };
2143
+ if (!item) {
2144
+ this.unsettle(device);
2145
+ if (!stat && this.root.snapshot.has(device)) this.depart(device);
2146
+ return;
2147
+ }
2148
+ if (this.root.snapshot.has(device)) {
2149
+ if (!this.root.snapshot.knows(item)) this.record(item);
2150
+ return;
2151
+ }
2152
+ if (item.kind === "folder") {
2153
+ this.record(item);
2154
+ return;
2155
+ }
2156
+ const from = this.departedTwin(item);
2157
+ if (from) {
2158
+ this.unsettle(device);
2159
+ this.record(item, { movedFrom: from });
2160
+ return;
2161
+ }
2162
+ const before = this.settling.get(device);
2163
+ if (before && before.size === item.size && before.mtime === item.mtime) {
2164
+ this.unsettle(device);
2165
+ this.record(item);
2166
+ return;
2167
+ }
2168
+ if (before) clearTimeout(before.timer);
2169
+ const timer = setTimeout(() => {
2170
+ void this.observe(device).catch(() => void 0);
2171
+ }, this.root.createStableMs ?? CREATE_STABLE_MS);
2172
+ timer.unref?.();
2173
+ this.settling.set(device, { size: item.size, mtime: item.mtime, timer });
2174
+ }
2175
+ unsettle(devicePath) {
2176
+ const pending = this.settling.get(devicePath);
2177
+ if (pending) {
2178
+ clearTimeout(pending.timer);
2179
+ this.settling.delete(devicePath);
2180
+ }
2181
+ }
2182
+ /** A known file is gone from its path: a folder goes out at once (its children are not paired); a file waits for its twin. */
2183
+ depart(devicePath) {
2184
+ const known = this.root.snapshot.entry(devicePath);
2185
+ if (!known || known.kind !== "file") {
2186
+ this.forget(devicePath);
2187
+ return;
2188
+ }
2189
+ const before = this.departing.get(devicePath);
2190
+ if (before) clearTimeout(before.timer);
2191
+ const timer = setTimeout(() => {
2192
+ this.departing.delete(devicePath);
2193
+ if (this.root.snapshot.has(devicePath)) this.forget(devicePath);
2194
+ }, this.root.movePairMs ?? MOVE_PAIR_MS);
2195
+ timer.unref?.();
2196
+ this.departing.set(devicePath, { size: known.size, mtime: known.mtime, timer });
2197
+ }
2198
+ /** The departed file this new one is (same size and modified time, and the only such), or null. */
2199
+ departedTwin(item) {
2200
+ if (item.kind !== "file") return null;
2201
+ let match = null;
2202
+ for (const [path14, d] of this.departing) {
2203
+ if (d.size !== item.size || d.mtime !== item.mtime) continue;
2204
+ if (match) return null;
2205
+ match = path14;
2206
+ }
2207
+ if (!match) return null;
2208
+ clearTimeout(this.departing.get(match).timer);
2209
+ this.departing.delete(match);
2210
+ return match;
2211
+ }
2212
+ /**
2213
+ * Walk the root against its snapshot and journal what changed (snapshot.ts). The root must be the shared folder
2214
+ * before and after; one walk runs at a time; a new file written moments ago settles through `observe` first.
2215
+ */
2216
+ async rescan() {
2217
+ if (!this.present()) throw this.lost();
2218
+ try {
2219
+ const result = await this.root.snapshot.rescan(this.rootPath, this.root.journal, {
2220
+ stillThere: () => this.present(),
2221
+ hold: (item) => !!item.mtime && Math.abs(Date.now() - Date.parse(item.mtime)) < RECENT_WRITE_MS,
2222
+ onFolder: (abs) => {
2223
+ void sweepTempFiles(abs).catch(() => void 0);
2224
+ }
2225
+ });
2226
+ for (const p of result.held) void this.observe(p).catch(() => void 0);
2227
+ return result;
2228
+ } catch (error) {
2229
+ if (!this.present()) throw this.lost();
2230
+ throw error;
2231
+ }
2232
+ }
2233
+ /** A rescan is walking now (the host does not start another). */
2234
+ get rescanning() {
2235
+ return this.root.snapshot.busy;
2236
+ }
2237
+ /** Stop waiting on new files (the root is closing). What had departed is reported gone: nothing is left unsaid. */
2238
+ stop() {
2239
+ void this.root.snapshot.persistNow();
2240
+ for (const pending of this.settling.values()) clearTimeout(pending.timer);
2241
+ this.settling.clear();
2242
+ for (const [path14, d] of this.departing) {
2243
+ clearTimeout(d.timer);
2244
+ if (this.root.snapshot.has(path14)) this.forget(path14);
2245
+ }
2246
+ this.departing.clear();
2247
+ void this.abortAllWrites();
2248
+ }
2249
+ /** For tests and the CLI: the parent and name a path has. */
2250
+ static split(devicePath) {
2251
+ const p = normalizeDevicePath(devicePath);
2252
+ return { parent: deviceDirname(p), name: deviceBasename(p) };
2253
+ }
2254
+ static join = deviceJoin;
2255
+ };
2256
+ function sameEntry(from, to) {
2257
+ if (from.device.toLowerCase() !== to.device.toLowerCase()) return false;
2258
+ let a;
2259
+ let b;
2260
+ try {
2261
+ a = import_fs11.default.lstatSync(from.abs);
2262
+ b = import_fs11.default.lstatSync(to.abs);
2263
+ } catch {
2264
+ return false;
2265
+ }
2266
+ return a.ino === 0 ? true : a.dev === b.dev && a.ino === b.ino;
2267
+ }
2268
+
2269
+ // src/syncFolders.ts
2270
+ var import_path11 = __toESM(require("path"));
2271
+ var DARWIN = [
2272
+ { provider: "dropbox", pattern: "Dropbox" },
2273
+ { provider: "dropbox", pattern: "Library/CloudStorage/Dropbox*" },
2274
+ { provider: "onedrive", pattern: "OneDrive*" },
2275
+ { provider: "onedrive", pattern: "Library/CloudStorage/OneDrive*" },
2276
+ { provider: "google_drive", pattern: "Google Drive*" },
2277
+ { provider: "google_drive", pattern: "Library/CloudStorage/GoogleDrive*" },
2278
+ { provider: "icloud", pattern: "Library/Mobile Documents/com~apple~CloudDocs" },
2279
+ { provider: "box", pattern: "Library/CloudStorage/Box*" },
2280
+ { provider: "box", pattern: "Box" }
2281
+ ];
2282
+ var WIN32 = [
2283
+ { provider: "dropbox", pattern: "Dropbox" },
2284
+ { provider: "onedrive", pattern: "OneDrive*" },
2285
+ { provider: "google_drive", pattern: "Google Drive*" },
2286
+ { provider: "google_drive", pattern: "My Drive" },
2287
+ { provider: "icloud", pattern: "iCloudDrive" },
2288
+ { provider: "box", pattern: "Box" }
2289
+ ];
2290
+ var LINUX = [
2291
+ { provider: "dropbox", pattern: "Dropbox" }
2292
+ ];
2293
+ var ABSOLUTE_DARWIN = [{ provider: "google_drive", prefix: "/Volumes/GoogleDrive" }];
2294
+ function segmentsMatch(have, want) {
2295
+ if (have.length < want.length) return false;
2296
+ return want.every((w, i) => {
2297
+ const h = have[i];
2298
+ if (w.endsWith("*")) return h.toLowerCase().startsWith(w.slice(0, -1).toLowerCase());
2299
+ return h.toLowerCase() === w.toLowerCase();
2300
+ });
2301
+ }
2302
+ function cloudSyncOf(absPath, options) {
2303
+ const abs = import_path11.default.resolve(absPath);
2304
+ if (options.platform === "darwin") {
2305
+ for (const r of ABSOLUTE_DARWIN) if (abs === r.prefix || abs.startsWith(`${r.prefix}${import_path11.default.sep}`) || abs.startsWith(`${r.prefix}-`)) return r.provider;
2306
+ }
2307
+ const home = import_path11.default.resolve(options.home);
2308
+ if (abs !== home && !abs.startsWith(`${home}${import_path11.default.sep}`)) return null;
2309
+ const rel = abs === home ? [] : abs.slice(home.length + 1).split(import_path11.default.sep);
2310
+ const rules = options.platform === "darwin" ? DARWIN : options.platform === "win32" ? WIN32 : LINUX;
2311
+ for (const rule of rules) {
2312
+ if (segmentsMatch(rel, rule.pattern.split("/"))) return rule.provider;
2313
+ }
2314
+ return null;
2315
+ }
2316
+
2317
+ // src/index.ts
2318
+ var import_os3 = __toESM(require("os"));
2319
+
2320
+ // src/watcher.ts
2321
+ var import_fs12 = __toESM(require("fs"));
2322
+ var import_path12 = __toESM(require("path"));
2323
+ var SETTLE_MS = 1500;
2324
+ var WATCH_BUDGET = Math.max(100, Number(process.env.TDAI_WATCH_BUDGET) || 2e4);
2325
+ var PENDING_MAX = 1e4;
2326
+ var RootWatcher = class {
2327
+ constructor(rootPath, ops, log, onSeenOrOptions) {
2328
+ this.rootPath = rootPath;
2329
+ this.ops = ops;
2330
+ this.log = log;
2331
+ this.rootReal = import_fs12.default.realpathSync(rootPath);
2332
+ this.options = typeof onSeenOrOptions === "function" ? { onSeen: onSeenOrOptions } : onSeenOrOptions ?? {};
2333
+ }
2334
+ recursive = null;
2335
+ /** Linux: one watcher per folder, by its device path. */
2336
+ folders = /* @__PURE__ */ new Map();
2337
+ pending = /* @__PURE__ */ new Map();
2338
+ rootReal;
2339
+ queue = Promise.resolve();
2340
+ stopped = false;
2341
+ collapsed = false;
2342
+ options;
2343
+ /** How this platform watches. */
2344
+ get strategy() {
2345
+ return this.options.strategy ?? (process.platform === "linux" ? "perFolder" : "recursive");
2346
+ }
2347
+ /** Folders under watch (per-folder strategy); 1 for a recursive watch; 0 when not watching. */
2348
+ get watchCount() {
2349
+ return this.recursive ? 1 : this.folders.size;
2350
+ }
2351
+ /**
2352
+ * True when events flow; false when this filesystem gives none, or the tree is past the budget (the rescan is the
2353
+ * feed then). Async because the per-folder watcher lists the tree without blocking the socket.
2354
+ */
2355
+ async start() {
2356
+ this.stopped = false;
2357
+ if (this.strategy === "recursive") return this.startRecursive();
2358
+ return this.startPerFolder();
2359
+ }
2360
+ startRecursive() {
2361
+ try {
2362
+ this.recursive = import_fs12.default.watch(this.rootReal, { recursive: true, persistent: true }, (_event, filename) => {
2363
+ if (!filename) return;
2364
+ const rel = filename.toString();
2365
+ const parts = rel.split(/[\\/]/);
2366
+ if (parts.some(isIgnoredName)) return;
2367
+ this.options.onSeen?.();
2368
+ this.schedule(normalizeDevicePath(parts.join("/")));
2369
+ });
2370
+ this.recursive.on("error", (error) => this.died(`watch error: ${error.message}`));
2371
+ return true;
2372
+ } catch (error) {
2373
+ this.log(`cannot watch ${this.rootPath}: ${error.message}; relying on the periodic rescan`);
2374
+ return false;
2375
+ }
2376
+ }
2377
+ async startPerFolder() {
2378
+ const budget = this.options.budget ?? WATCH_BUDGET;
2379
+ try {
2380
+ if (!this.watchFolder("")) throw new Error("the root could not be watched");
2381
+ const stack = [""];
2382
+ while (stack.length && !this.stopped) {
2383
+ const folder = stack.pop();
2384
+ const abs = folder === "" ? this.rootReal : import_path12.default.join(this.rootReal, ...folder.slice(1).split("/"));
2385
+ let entries;
2386
+ try {
2387
+ entries = await import_fs12.default.promises.readdir(abs, { withFileTypes: true });
2388
+ } catch {
2389
+ continue;
2390
+ }
2391
+ for (const entry of entries) {
2392
+ if (!entry.isDirectory() || isIgnoredName(entry.name)) continue;
2393
+ const child = deviceJoin(folder, entry.name);
2394
+ if (this.folders.size >= budget) throw new Error(`more than ${budget} folders`);
2395
+ if (!this.watchFolder(child)) throw new Error("the kernel refused a watch (inotify limit)");
2396
+ stack.push(child);
2397
+ }
2398
+ }
2399
+ if (this.stopped) return false;
2400
+ return true;
2401
+ } catch (error) {
2402
+ this.closeAll();
2403
+ this.log(`cannot watch ${this.rootPath}: ${error.message}; relying on the periodic rescan`);
2404
+ return false;
2405
+ }
2406
+ }
2407
+ /** One folder's watch; false when the kernel refuses (ENOSPC: the inotify limit, EMFILE). */
2408
+ watchFolder(folder) {
2409
+ if (this.folders.has(folder)) return true;
2410
+ const abs = folder === "" ? this.rootReal : import_path12.default.join(this.rootReal, ...folder.slice(1).split("/"));
2411
+ try {
2412
+ const watcher = import_fs12.default.watch(abs, { persistent: true }, (_event, filename) => {
2413
+ if (!filename) {
2414
+ this.schedule(folder || "");
2415
+ return;
2416
+ }
2417
+ const name = filename.toString();
2418
+ if (isIgnoredName(name)) return;
2419
+ this.options.onSeen?.();
2420
+ this.schedule(deviceJoin(folder, name));
2421
+ });
2422
+ watcher.on("error", (error) => {
2423
+ const code = error.code;
2424
+ if (code === "ENOENT") {
2425
+ this.unwatchFolder(folder);
2426
+ return;
2427
+ }
2428
+ this.died(`watch error on ${folder || "/"}: ${error.message}`);
2429
+ });
2430
+ this.folders.set(folder, watcher);
2431
+ return true;
2432
+ } catch {
2433
+ return false;
2434
+ }
2435
+ }
2436
+ unwatchFolder(folder) {
2437
+ const prefix = `${folder}/`;
2438
+ for (const [key, watcher] of [...this.folders]) {
2439
+ if (key === folder || folder !== "" && key.startsWith(prefix)) {
2440
+ watcher.close();
2441
+ this.folders.delete(key);
2442
+ }
2443
+ }
2444
+ }
2445
+ died(reason) {
2446
+ if (this.stopped) return;
2447
+ this.log(`${reason}; relying on the periodic rescan`);
2448
+ this.stop();
2449
+ try {
2450
+ this.options.onError?.(reason);
2451
+ } catch {
2452
+ }
2453
+ }
2454
+ closeAll() {
2455
+ this.recursive?.close();
2456
+ this.recursive = null;
2457
+ for (const watcher of this.folders.values()) watcher.close();
2458
+ this.folders.clear();
2459
+ }
2460
+ stop() {
2461
+ this.stopped = true;
2462
+ this.closeAll();
2463
+ for (const t of this.pending.values()) clearTimeout(t);
2464
+ this.pending.clear();
2465
+ }
2466
+ schedule(devicePath) {
2467
+ const existing = this.pending.get(devicePath);
2468
+ if (existing) clearTimeout(existing);
2469
+ if (!existing && this.pending.size >= PENDING_MAX) {
2470
+ if (!this.collapsed) {
2471
+ this.collapsed = true;
2472
+ this.log(`more than ${PENDING_MAX} paths changed at once; rescanning instead of following each`);
2473
+ for (const t of this.pending.values()) clearTimeout(t);
2474
+ this.pending.clear();
2475
+ this.queue = this.queue.then(() => this.ops.rescan().then(() => void 0)).catch(() => void 0).finally(() => {
2476
+ this.collapsed = false;
2477
+ });
2478
+ }
2479
+ return;
2480
+ }
2481
+ const timer = setTimeout(() => {
2482
+ this.pending.delete(devicePath);
2483
+ this.queue = this.queue.then(() => this.observe(devicePath)).catch(() => void 0);
2484
+ }, SETTLE_MS);
2485
+ timer.unref?.();
2486
+ this.pending.set(devicePath, timer);
2487
+ }
2488
+ async observe(devicePath) {
2489
+ const known = this.ops.knows(devicePath);
2490
+ await this.ops.observe(devicePath);
2491
+ const abs = import_path12.default.join(this.rootReal, ...devicePath.slice(1).split("/"));
2492
+ let isDir = false;
2493
+ try {
2494
+ isDir = import_fs12.default.statSync(abs).isDirectory();
2495
+ } catch {
2496
+ return;
2497
+ }
2498
+ if (!isDir) return;
2499
+ if (this.strategy === "perFolder" && !this.folders.has(devicePath)) {
2500
+ if (this.folders.size >= (this.options.budget ?? WATCH_BUDGET) || !this.watchFolder(devicePath)) {
2501
+ this.died(`the folder budget ran out at ${devicePath}`);
2502
+ return;
2503
+ }
2504
+ }
2505
+ if (!known) for await (const child of walkAll(this.rootPath, devicePath)) {
2506
+ await this.ops.observe(child.externalId);
2507
+ if (child.kind === "folder" && this.strategy === "perFolder" && !this.stopped) this.watchFolder(child.externalId);
2508
+ }
2509
+ }
2510
+ /** Tests: wait for queued observations. */
2511
+ settle() {
2512
+ return this.queue;
2513
+ }
2514
+ };
2515
+
2516
+ // src/client.ts
2517
+ var import_fs13 = __toESM(require("fs"));
2518
+ var import_crypto4 = require("crypto");
2519
+ var WRITES = /* @__PURE__ */ new Set(["mkdir", "move", "copy", "trash", "write", "write_open", "write_close"]);
2520
+ var REPLY_MEMORY_MS = 5 * 6e4;
2521
+ var REPLY_MEMORY_MAX = 2e3;
2522
+ var CHUNK_ACK_WAIT_MS = 15 * 6e4;
2523
+ var RecentReplies = class {
2524
+ constructor(ttlMs = REPLY_MEMORY_MS, max = REPLY_MEMORY_MAX, now = Date.now) {
2525
+ this.ttlMs = ttlMs;
2526
+ this.max = max;
2527
+ this.now = now;
2528
+ }
2529
+ byId = /* @__PURE__ */ new Map();
2530
+ once(id, run) {
2531
+ const at = this.now();
2532
+ this.evict(at);
2533
+ const known = this.byId.get(id);
2534
+ if (known) return known.reply;
2535
+ const entry = { at, settled: false, reply: run() };
2536
+ entry.reply.then(() => {
2537
+ entry.at = this.now();
2538
+ entry.settled = true;
2539
+ }, () => {
2540
+ entry.at = this.now();
2541
+ entry.settled = true;
2542
+ });
2543
+ this.byId.set(id, entry);
2544
+ return entry.reply;
2545
+ }
2546
+ evict(at) {
2547
+ let oldest = null;
2548
+ let oldestAt = Infinity;
2549
+ for (const [key, entry] of this.byId) {
2550
+ if (!entry.settled) continue;
2551
+ if (at - entry.at >= this.ttlMs) {
2552
+ this.byId.delete(key);
2553
+ continue;
2554
+ }
2555
+ if (entry.at < oldestAt) {
2556
+ oldestAt = entry.at;
2557
+ oldest = key;
2558
+ }
2559
+ }
2560
+ if (this.byId.size >= this.max && oldest) this.byId.delete(oldest);
2561
+ }
2562
+ /** Test seam. */
2563
+ get size() {
2564
+ return this.byId.size;
2565
+ }
2566
+ };
2567
+ var DeviceClient = class {
2568
+ constructor(deps) {
2569
+ this.deps = deps;
2570
+ }
2571
+ replies = new RecentReplies();
2572
+ aborted = /* @__PURE__ */ new Set();
2573
+ open = /* @__PURE__ */ new Set();
2574
+ /** Write streams the server has open, by stream, with the root they write into. */
2575
+ writing = /* @__PURE__ */ new Map();
2576
+ pendingNudges = /* @__PURE__ */ new Map();
2577
+ /** Another copy of this device connected with the same token: this one stays down rather than fight it. */
2578
+ superseded = false;
2579
+ /** Hellos the server refused in a row (an unsupported protocol, a token of another device): each wait doubles. */
2580
+ refusals = 0;
2581
+ /**
2582
+ * A root's journal moved: nudge the server once the burst settles (a save writes a file three times; a
2583
+ * download lands a thousand). The nudge carries only the position; the server reads from its own cursor, so
2584
+ * one lost while offline costs nothing: the server's catch-up and the next nudge both read the same feed.
2585
+ */
2586
+ notifyChanged(rootId) {
2587
+ const pending = this.pendingNudges.get(rootId);
2588
+ if (pending) clearTimeout(pending);
2589
+ const timer = setTimeout(() => {
2590
+ this.pendingNudges.delete(rootId);
2591
+ if (!this.deps.socket.connected) return;
2592
+ const root = this.deps.roots().find((r) => r.announce.id === rootId);
2593
+ if (!root) return;
2594
+ try {
2595
+ this.deps.socket.emit("changed", { root: rootId, cursor: root.ops.position });
2596
+ } catch {
2597
+ }
2598
+ }, this.deps.changeDebounceMs ?? 1500);
2599
+ timer.unref?.();
2600
+ this.pendingNudges.set(rootId, timer);
2601
+ }
2602
+ start() {
2603
+ const { socket } = this.deps;
2604
+ socket.on("connect", () => {
2605
+ this.announce();
2606
+ for (const root of this.deps.roots()) this.notifyChanged(root.announce.id);
2607
+ });
2608
+ socket.on("disconnect", (reason) => {
2609
+ this.deps.log(`disconnected (${reason}); reconnecting`);
2610
+ for (const s of this.open) this.aborted.add(s);
2611
+ for (const [s, ops] of this.writing) {
2612
+ void ops.abortWrite(s);
2613
+ }
2614
+ this.writing.clear();
2615
+ if (this.superseded) {
2616
+ this.deps.log("another copy of this device connected with the same token; this one stopped. Pair this copy on its own (tdai-device pair) to run both.");
2617
+ return;
2618
+ }
2619
+ if (reason === "io server disconnect" && socket.connect) {
2620
+ const base = this.deps.reconnectAfterMs ?? 5e3;
2621
+ const wait = Math.min(base * 2 ** Math.min(this.refusals, 10), Math.max(base, 10 * 6e4));
2622
+ const timer = setTimeout(() => {
2623
+ if (!socket.connected) socket.connect?.();
2624
+ }, wait);
2625
+ timer.unref?.();
2626
+ }
2627
+ });
2628
+ socket.on("connect_error", (error) => this.deps.log(`cannot connect: ${error.message}`));
2629
+ socket.on("rpc", (request, ack) => {
2630
+ void this.handle(request).then(ack);
2631
+ });
2632
+ socket.on("stream_abort", (abort) => {
2633
+ if (this.open.has(abort.stream)) this.aborted.add(abort.stream);
2634
+ const writing = this.writing.get(abort.stream);
2635
+ if (writing) {
2636
+ this.writing.delete(abort.stream);
2637
+ void writing.abortWrite(abort.stream);
2638
+ }
2639
+ });
2640
+ socket.on("write_chunk", (chunk, ack) => {
2641
+ const ops = chunk && typeof chunk === "object" ? this.writing.get(chunk.stream) : void 0;
2642
+ if (!ops) {
2643
+ ack(false);
2644
+ return;
2645
+ }
2646
+ ops.appendWrite(chunk).then(ack, () => {
2647
+ this.writing.delete(chunk.stream);
2648
+ ack(false);
2649
+ });
2650
+ });
2651
+ socket.on("superseded", () => {
2652
+ this.superseded = true;
2653
+ });
2654
+ }
2655
+ announce() {
2656
+ const retired = this.deps.retired?.() ?? [];
2657
+ const hello = { protocol: DEVICE_PROTOCOL_VERSION, device: this.deps.device, roots: this.deps.roots().map((r) => r.announce), ...retired.length ? { retired } : {} };
2658
+ this.deps.socket.emit("hello", hello, (reply) => {
2659
+ if (reply?.ok && retired.length) this.deps.retiredAcked?.(retired);
2660
+ const refused = Array.isArray(reply?.retire) ? reply.retire.filter((id) => typeof id === "string") : [];
2661
+ if (reply?.ok && refused.length) {
2662
+ this.deps.log(`stopped sharing ${refused.length} folder(s) that were removed while this device was away`);
2663
+ this.deps.retireRequested?.(refused);
2664
+ }
2665
+ if (reply?.ok) {
2666
+ this.refusals = 0;
2667
+ this.deps.log(`connected as ${this.deps.device.name}: ${hello.roots.length} folder(s) shared`);
2668
+ } else {
2669
+ this.refusals += 1;
2670
+ this.deps.log(`the server refused this device: ${reply?.error ?? "no reason given"}`);
2671
+ }
2672
+ });
2673
+ }
2674
+ rootOps(rootId) {
2675
+ const found = this.deps.roots().find((r) => r.announce.id === rootId);
2676
+ if (!found) throw new OpError("NOT_FOUND", `no shared folder ${rootId}`);
2677
+ return found.ops;
2678
+ }
2679
+ /**
2680
+ * One RPC. A write the server sends again under the same request id (its ack timed out; the first may have
2681
+ * finished, or still be running) gets the first one's answer, never a second run on a half-finished op.
2682
+ */
2683
+ handle(request) {
2684
+ if (!request || typeof request !== "object" || !WRITES.has(request.method) || typeof request.id !== "string" || !request.id) return this.dispatch(request);
2685
+ return this.replies.once(request.id, () => this.dispatch(request));
2686
+ }
2687
+ async dispatch(request) {
2688
+ try {
2689
+ if (!request || typeof request !== "object" || typeof request.method !== "string") return { ok: false, error: { code: "UNSUPPORTED", message: "malformed request" } };
2690
+ const params = request.params ?? {};
2691
+ const ops = this.rootOps(String(params.root ?? ""));
2692
+ switch (request.method) {
2693
+ case "stat":
2694
+ return { ok: true, result: await ops.stat(params) };
2695
+ case "list":
2696
+ return { ok: true, result: await ops.list(params) };
2697
+ case "enumerate":
2698
+ return { ok: true, result: await ops.enumerate(params) };
2699
+ case "changes":
2700
+ return { ok: true, result: await ops.changes(params) };
2701
+ case "mkdir":
2702
+ return { ok: true, result: await ops.mkdir(params) };
2703
+ case "move":
2704
+ return { ok: true, result: await ops.move(params) };
2705
+ case "copy":
2706
+ return { ok: true, result: await ops.copy(params) };
2707
+ case "trash":
2708
+ return { ok: true, result: await ops.trash(params) };
2709
+ case "write":
2710
+ return { ok: true, result: await ops.write(params) };
2711
+ case "write_open": {
2712
+ const opened = await ops.openWrite(params);
2713
+ this.writing.set(opened.stream, ops);
2714
+ return { ok: true, result: opened };
2715
+ }
2716
+ case "write_close": {
2717
+ const stream = String(params.stream ?? "");
2718
+ this.writing.delete(stream);
2719
+ return { ok: true, result: await ops.closeWrite(params) };
2720
+ }
2721
+ case "hash":
2722
+ return { ok: true, result: await ops.hash(params) };
2723
+ case "media":
2724
+ return { ok: true, result: await ops.media(params) };
2725
+ case "read": {
2726
+ const opened = ops.openRead(params);
2727
+ const named = typeof params.stream === "string" && /^[0-9a-f-]{36}$/i.test(params.stream) ? params.stream : null;
2728
+ const stream = named ?? (0, import_crypto4.randomUUID)();
2729
+ this.open.add(stream);
2730
+ setImmediate(() => {
2731
+ void this.pump(stream, opened.abs);
2732
+ });
2733
+ return { ok: true, result: { stream, size: opened.size, mimeType: "application/octet-stream" } };
2734
+ }
2735
+ default:
2736
+ return { ok: false, error: { code: "UNSUPPORTED", message: `unknown method ${String(request.method)}` } };
2737
+ }
2738
+ } catch (error) {
2739
+ const e = toOpError(error);
2740
+ return { ok: false, error: { code: e.code, message: e.message } };
2741
+ }
2742
+ }
2743
+ async pump(stream, abs) {
2744
+ const size = this.deps.chunkBytes ?? STREAM_CHUNK_BYTES;
2745
+ let seq = 0;
2746
+ const file = import_fs13.default.createReadStream(abs, { highWaterMark: size });
2747
+ try {
2748
+ let last = null;
2749
+ for await (const part of file) {
2750
+ if (this.aborted.has(stream)) break;
2751
+ if (last) {
2752
+ if (!await this.send({ stream, seq, data: last, last: false })) {
2753
+ this.aborted.add(stream);
2754
+ break;
2755
+ }
2756
+ seq += 1;
2757
+ }
2758
+ last = part;
2759
+ }
2760
+ if (!this.aborted.has(stream)) await this.send({ stream, seq, data: last ?? Buffer.alloc(0), last: true });
2761
+ } catch (error) {
2762
+ this.deps.log(`read of ${abs} failed: ${error.message}`);
2763
+ } finally {
2764
+ file.destroy();
2765
+ this.open.delete(stream);
2766
+ this.aborted.delete(stream);
2767
+ }
2768
+ }
2769
+ async send(chunk) {
2770
+ try {
2771
+ return await this.deps.socket.timeout(CHUNK_ACK_WAIT_MS).emitWithAck("chunk", chunk) === true;
2772
+ } catch {
2773
+ return false;
2774
+ }
2775
+ }
2776
+ };
2777
+
2778
+ // src/identity.ts
2779
+ var import_fs14 = __toESM(require("fs"));
2780
+ var import_path13 = __toESM(require("path"));
2781
+ function identityOf(rootPath) {
2782
+ let stat;
2783
+ try {
2784
+ stat = import_fs14.default.statSync(rootPath);
2785
+ } catch {
2786
+ return null;
2787
+ }
2788
+ if (!stat.isDirectory()) return null;
2789
+ let parent = null;
2790
+ try {
2791
+ parent = import_fs14.default.statSync(import_path13.default.dirname(import_path13.default.resolve(rootPath)));
2792
+ } catch {
2793
+ }
2794
+ const mount = !parent || parent.dev !== stat.dev || parent.ino === stat.ino;
2795
+ return { dev: stat.dev, ino: stat.ino, mount };
2796
+ }
2797
+ function sameRoot(recorded, now) {
2798
+ if (recorded.dev === now.dev && recorded.ino === now.ino) return true;
2799
+ if (recorded.mount && !now.mount) return false;
2800
+ if (recorded.dev !== now.dev && recorded.ino !== now.ino) return false;
2801
+ return true;
2802
+ }
2803
+ var RootIdentityStore = class {
2804
+ file;
2805
+ recorded;
2806
+ constructor(dir) {
2807
+ this.file = import_path13.default.join(dir, "root.json");
2808
+ }
2809
+ load() {
2810
+ if (this.recorded !== void 0) return this.recorded;
2811
+ try {
2812
+ const parsed = JSON.parse(import_fs14.default.readFileSync(this.file, "utf8"));
2813
+ this.recorded = typeof parsed.dev === "number" && typeof parsed.ino === "number" ? { dev: parsed.dev, ino: parsed.ino, mount: parsed.mount === true } : null;
2814
+ } catch {
2815
+ this.recorded = null;
2816
+ }
2817
+ return this.recorded;
2818
+ }
2819
+ save(identity) {
2820
+ this.recorded = identity;
2821
+ try {
2822
+ import_fs14.default.mkdirSync(import_path13.default.dirname(this.file), { recursive: true });
2823
+ import_fs14.default.writeFileSync(`${this.file}.tmp`, JSON.stringify(identity));
2824
+ import_fs14.default.renameSync(`${this.file}.tmp`, this.file);
2825
+ } catch {
2826
+ }
2827
+ }
2828
+ /**
2829
+ * `ok` when the folder at the path is the shared one (recorded on first sight, and the record follows a disk
2830
+ * that was renumbered); `missing` when nothing is there; `changed` when another folder stands in its place.
2831
+ */
2832
+ check(rootPath) {
2833
+ const now = identityOf(rootPath);
2834
+ if (!now) return "missing";
2835
+ const recorded = this.load();
2836
+ if (!recorded) {
2837
+ this.save(now);
2838
+ return "ok";
2839
+ }
2840
+ if (!sameRoot(recorded, now)) return "changed";
2841
+ if (recorded.dev !== now.dev || recorded.ino !== now.ino || recorded.mount !== now.mount) this.save(now);
2842
+ return "ok";
2843
+ }
2844
+ /**
2845
+ * Take the folder now at the path as the root, whatever its numbers. Asked when `check` said `changed` and the
2846
+ * folder's CONTENT says otherwise (`looksLikeSharedFolder`), or by the person (`tdai-device root re-adopt`). Device
2847
+ * and inode numbers are not a stable identity on every filesystem: cifs mounted `noserverino` makes them up per
2848
+ * mount, a volume restored from backup has new ones, exFAT invents them at mount; a root read as `missing` for good
2849
+ * for that reason was the review's finding.
2850
+ */
2851
+ adopt(rootPath) {
2852
+ const now = identityOf(rootPath);
2853
+ if (!now) return false;
2854
+ this.save(now);
2855
+ return true;
2856
+ }
2857
+ /** Forget the record: the next probe records whatever stands at the path. */
2858
+ forget() {
2859
+ this.recorded = void 0;
2860
+ try {
2861
+ import_fs14.default.unlinkSync(this.file);
2862
+ } catch {
2863
+ }
2864
+ }
2865
+ };
2866
+ var ADOPT_SHARE = 0.6;
2867
+ var ADOPT_MIN_KNOWN = 3;
2868
+ function looksLikeSharedFolder(rootPath, knownTopLevelNames) {
2869
+ if (knownTopLevelNames.length < ADOPT_MIN_KNOWN) return false;
2870
+ let present;
2871
+ try {
2872
+ present = new Set(import_fs14.default.readdirSync(rootPath));
2873
+ } catch {
2874
+ return false;
2875
+ }
2876
+ const found = knownTopLevelNames.filter((name) => present.has(name)).length;
2877
+ return found >= Math.ceil(knownTopLevelNames.length * ADOPT_SHARE);
2878
+ }
2879
+
2880
+ // src/index.ts
2881
+ var HELPER_VERSION = "0.1.4";
2882
+ var WATCHER_RETRY_MS = 5 * 6e4;
2883
+ function probeRoot(rootPath, identity, options = {}) {
2884
+ try {
2885
+ if (!import_fs15.default.statSync(rootPath).isDirectory()) return "missing";
2886
+ } catch {
2887
+ return "missing";
2888
+ }
2889
+ if (identity) {
2890
+ const verdict = identity.check(rootPath);
2891
+ if (verdict === "missing") return "missing";
2892
+ if (verdict === "changed") {
2893
+ const names = options.knownTopLevelNames?.() ?? [];
2894
+ if (!looksLikeSharedFolder(rootPath, names) || !identity.adopt(rootPath)) return "missing";
2895
+ options.log?.(`${rootPath}: the volume was renumbered but holds the shared folder's files; adopted as the same root`);
2896
+ }
2897
+ }
2898
+ try {
2899
+ import_fs15.default.closeSync(import_fs15.default.openSync(rootPath, "r"));
2900
+ import_fs15.default.readdirSync(rootPath);
2901
+ return "ok";
2902
+ } catch (error) {
2903
+ const code = error.code;
2904
+ return code === "EPERM" || code === "EACCES" ? "denied" : "missing";
2905
+ }
2906
+ }
2907
+ async function bringUpRoot(config, log, options = {}) {
2908
+ const dir = stateDir(config.id);
2909
+ try {
2910
+ markTrashDir(config);
2911
+ } catch (error) {
2912
+ log(`${config.label}: the trash folder could not be marked (${error.message}); what is in it may be listed`);
2913
+ }
2914
+ const journal = new Journal(dir);
2915
+ journal.load();
2916
+ const snapshot = new Snapshot(dir);
2917
+ const identity = new RootIdentityStore(dir);
2918
+ const hadSnapshot = snapshot.load();
2919
+ const probe = () => probeRoot(config.path, identity, { knownTopLevelNames: () => snapshot.topLevelNames(), log: (line) => log(`${config.label}: ${line}`) });
2920
+ const runtime = { config, journal, snapshot, identity, state: probe() };
2921
+ const ops = new RootOps(runtime);
2922
+ const syncOf = cloudSyncOf(config.path, { home: import_os3.default.homedir(), platform: process.platform });
2923
+ const announce = () => ({
2924
+ id: config.id,
2925
+ label: config.label,
2926
+ trash: rootHasTrash(config),
2927
+ readOnly: config.readOnly,
2928
+ content: config.content,
2929
+ ...config.shared ? { shared: true } : {},
2930
+ ...runtime.state && runtime.state !== "ok" ? { state: runtime.state } : {},
2931
+ ...syncOf ? { syncOf } : {}
2932
+ });
2933
+ const live = {
2934
+ announce: announce(),
2935
+ ops,
2936
+ runtime,
2937
+ watcher: null,
2938
+ state: runtime.state,
2939
+ reason: rootStateReason(runtime.state, config.label),
2940
+ reprobe: async () => {
2941
+ const next = probe();
2942
+ if (next === runtime.state) return false;
2943
+ runtime.state = next;
2944
+ live.state = next;
2945
+ live.reason = rootStateReason(next, config.label);
2946
+ live.announce = announce();
2947
+ if (next === "ok") await open();
2948
+ else close();
2949
+ return true;
2950
+ }
2951
+ };
2952
+ journal.onRecord = () => options.onChanged?.(live);
2953
+ runtime.onStateChange = (state) => {
2954
+ if (live.state === state) return;
2955
+ live.state = state;
2956
+ live.reason = rootStateReason(state, config.label);
2957
+ live.announce = announce();
2958
+ close();
2959
+ options.onStateChange?.(live);
2960
+ };
2961
+ const close = () => {
2962
+ live.watcher?.stop();
2963
+ live.watcher = null;
2964
+ if (watcherRetry) {
2965
+ clearTimeout(watcherRetry);
2966
+ watcherRetry = null;
2967
+ }
2968
+ ops.stop();
2969
+ };
2970
+ const open = async () => {
2971
+ const had = hadSnapshot || snapshot.exists;
2972
+ const started = Date.now();
2973
+ const result = await ops.rescan();
2974
+ log(`${config.label}: ${result.seen} items${had ? ` (+${result.added} ~${result.changed} -${result.removed} since last run)` : ""} in ${Math.round((Date.now() - started) / 1e3)} s`);
2975
+ logRescanDoubts(config, result, log);
2976
+ live.watcher = await startWatcher();
2977
+ };
2978
+ let watcherRetry = null;
2979
+ const startWatcher = async () => {
2980
+ const watcher = new RootWatcher(config.path, ops, (line) => log(`${config.label}: ${line}`), {
2981
+ onSeen: () => options.onSeen?.(live),
2982
+ onError: () => {
2983
+ live.watcher = null;
2984
+ if (runtime.state === "ok" && !ops.rescanning) void ops.rescan().then((r) => logRescanDoubts(config, r, log)).catch((error) => log(`${config.label}: rescan failed: ${error.message}`));
2985
+ if (watcherRetry) clearTimeout(watcherRetry);
2986
+ watcherRetry = setTimeout(() => {
2987
+ watcherRetry = null;
2988
+ if (runtime.state === "ok" && !live.watcher) void startWatcher().then((w) => {
2989
+ live.watcher = w;
2990
+ });
2991
+ }, WATCHER_RETRY_MS);
2992
+ watcherRetry.unref?.();
2993
+ }
2994
+ });
2995
+ return await watcher.start() ? watcher : null;
2996
+ };
2997
+ if (runtime.state === "ok") {
2998
+ try {
2999
+ await open();
3000
+ } catch (error) {
3001
+ const code = error.code;
3002
+ runtime.state = code === "EPERM" || code === "EACCES" || error.name === "FolderDeniedError" ? "denied" : "missing";
3003
+ live.state = runtime.state;
3004
+ live.reason = rootStateReason(runtime.state, config.label);
3005
+ live.announce = announce();
3006
+ log(`${config.label}: ${live.reason}`);
3007
+ }
3008
+ } else {
3009
+ log(`${config.label}: ${live.reason}`);
3010
+ }
3011
+ if (syncOf) log(`${config.label}: this is your ${syncOf} folder; the server decides whether it is shared twice`);
3012
+ return live;
3013
+ }
3014
+ function logRescanDoubts(config, result, log) {
3015
+ if (result.skipped) log(`${config.label}: ${result.skipped} folder(s) left out by their marker (a virtualenv, the trash folder), with everything under them`);
3016
+ if (result.reset) log(`${config.label}: ${result.reset.changes} changes since the last look, more than the journal replays; the server re-lists the folder`);
3017
+ if (result.unreadable.length) log(`${config.label}: could not read ${result.unreadable.length} folder(s) (${result.unreadable.slice(0, 3).map((p) => p || "/").join(", ")}${result.unreadable.length > 3 ? ", \u2026" : ""}); what was known of them is kept`);
3018
+ if (result.refused) log(`${config.label}: ${result.refused.removing} of ${result.refused.of} items look deleted; that is not reported until you confirm it is real: tdai-device root accept-removals ${config.id}`);
3019
+ }
3020
+ // Annotate the CommonJS export names for ESM import in node:
3021
+ 0 && (module.exports = {
3022
+ DEVICE_NAMESPACE,
3023
+ DEVICE_PROTOCOL_VERSION,
3024
+ DeviceClient,
3025
+ HELPER_VERSION,
3026
+ RootOps,
3027
+ bringUpRoot,
3028
+ defaultDeviceName,
3029
+ deviceHome,
3030
+ devicePlatform,
3031
+ loadConfig,
3032
+ newRootId,
3033
+ rootHasTrash,
3034
+ saveConfig,
3035
+ stateDir
3036
+ });