@celljs/ta-sync 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/host/index.mjs +1164 -755
  2. package/package.json +4 -4
  3. package/web/index.js +175 -42
package/host/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // web-src/host.ts
2
- import { readFile as readFile5 } from "node:fs/promises";
3
- import { join as join7 } from "node:path";
2
+ import { readFile as readFile7 } from "node:fs/promises";
3
+ import { join as join9 } from "node:path";
4
4
 
5
5
  // web-src/migrate-protocol.ts
6
6
  var MIGRATE_CATEGORIES = [
@@ -23,15 +23,120 @@ var BACKUP_EXTENSION = ".tabackup";
23
23
  import { randomBytes as randomBytes3, randomUUID } from "node:crypto";
24
24
  import { createSocket } from "node:dgram";
25
25
  import { createReadStream, createWriteStream } from "node:fs";
26
- import { mkdir as mkdir3, readdir as readdir3, rename as rename3, rm as rm2, stat as stat3 } from "node:fs/promises";
26
+ import { mkdir as mkdir3, readdir as readdir4, rename as rename3, rm as rm2, stat as stat4 } from "node:fs/promises";
27
27
  import { createConnection, createServer } from "node:net";
28
- import { homedir as homedir2, hostname as hostname2 } from "node:os";
29
- import { join as join3 } from "node:path";
28
+ import { homedir as homedir3, hostname as hostname2 } from "node:os";
29
+ import { join as join4 } from "node:path";
30
30
 
31
31
  // web-src/migrate-archive.ts
32
- import { mkdir as mkdir2, readdir as readdir2, readFile as readFile2, rename as rename2, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
33
- import { homedir, hostname, platform } from "node:os";
34
- import { basename, dirname as dirname2, join as join2, relative as relative2, sep as sep2 } from "node:path";
32
+ import { mkdir as mkdir2, readdir as readdir3, readFile as readFile3, rename as rename2, stat as stat3, writeFile as writeFile2 } from "node:fs/promises";
33
+ import { homedir as homedir2, hostname, platform } from "node:os";
34
+ import { basename, dirname as dirname3, join as join3, relative as relative2, sep as sep2 } from "node:path";
35
+
36
+ // ../ta-protocol/esm/common/path-map.js
37
+ var TaPathMap;
38
+ (function(TaPathMap2) {
39
+ function isWindows(path2) {
40
+ return /^[a-zA-Z]:([\\/]|$)/.test(path2) || /^\\\\[^\\]/.test(path2);
41
+ }
42
+ TaPathMap2.isWindows = isWindows;
43
+ function rest(path2, base) {
44
+ const windows = isWindows(base);
45
+ if (windows ? !isWindows(path2) : !base.startsWith("/") || !path2.startsWith("/")) {
46
+ return;
47
+ }
48
+ const within = parts(base, windows);
49
+ const all = parts(path2, windows);
50
+ if (!within.length || all.length < within.length) {
51
+ return;
52
+ }
53
+ const same = (a, b) => windows ? a.toLowerCase() === b.toLowerCase() : a === b;
54
+ return within.every((part, i) => same(part, all[i])) ? all.slice(within.length) : undefined;
55
+ }
56
+ TaPathMap2.rest = rest;
57
+ function under(path2, base) {
58
+ return rest(path2, base) !== undefined;
59
+ }
60
+ TaPathMap2.under = under;
61
+ function join(base, parts2) {
62
+ if (!parts2.length) {
63
+ return base;
64
+ }
65
+ const sep = isWindows(base) ? "\\" : "/";
66
+ return `${base.replace(/[\\/]+$/, "")}${sep}${parts2.join(sep)}`;
67
+ }
68
+ TaPathMap2.join = join;
69
+ function basename(path2) {
70
+ var _a;
71
+ return (_a = path2.split(/[\\/]+/).filter(Boolean).pop()) !== null && _a !== undefined ? _a : "";
72
+ }
73
+ TaPathMap2.basename = basename;
74
+ function path(value, pairs) {
75
+ for (const [from, to] of deepest(pairs)) {
76
+ const found = rest(value, from);
77
+ if (found) {
78
+ return join(to, found);
79
+ }
80
+ }
81
+ return value;
82
+ }
83
+ TaPathMap2.path = path;
84
+ function text(value, pairs) {
85
+ const order = deepest(pairs);
86
+ if (!order.length) {
87
+ return value;
88
+ }
89
+ const end = String.raw`\s"'<>|*?:;,`;
90
+ const pattern = new RegExp(String.raw`(^|[^\w.~-])(?:${order.map(([from]) => `(${source(from)})`).join("|")})((?:[\\/][^\\/${end}]*)*)(?=$|[\\/${end})\]}])`, "g");
91
+ return value.replace(pattern, (...match) => {
92
+ var _a;
93
+ const before = match[1];
94
+ const found = order.findIndex((_, i) => match[i + 2] !== undefined);
95
+ const tail = (_a = match[order.length + 2]) !== null && _a !== undefined ? _a : "";
96
+ return `${before}${join(order[found][1], tail.split(/[\\/]+/).filter(Boolean))}`;
97
+ });
98
+ }
99
+ TaPathMap2.text = text;
100
+ function json(value, pairs) {
101
+ const order = deepest(pairs);
102
+ if (!order.length) {
103
+ return value;
104
+ }
105
+ const one = (each) => {
106
+ const whole = path(each, order);
107
+ return whole !== each ? whole : text(each, order);
108
+ };
109
+ const walk = (each) => {
110
+ if (typeof each === "string") {
111
+ return one(each);
112
+ }
113
+ if (Array.isArray(each)) {
114
+ return each.map(walk);
115
+ }
116
+ if (each && typeof each === "object") {
117
+ return Object.fromEntries(Object.entries(each).map(([key, inner]) => [one(key), walk(inner)]));
118
+ }
119
+ return each;
120
+ };
121
+ return walk(value);
122
+ }
123
+ TaPathMap2.json = json;
124
+ function parts(path2, windows) {
125
+ return path2.split(windows ? /[\\/]+/ : /\/+/).filter(Boolean);
126
+ }
127
+ function deepest(pairs) {
128
+ return pairs.filter(([from, to]) => from && to && from !== to && parts(from, isWindows(from)).length > 0).sort(([a], [b]) => parts(b, isWindows(b)).length - parts(a, isWindows(a)).length);
129
+ }
130
+ function source(base) {
131
+ const windows = isWindows(base);
132
+ const quote = (part) => [...part].map((char) => windows && char.toLowerCase() !== char.toUpperCase() ? `[${char.toLowerCase()}${char.toUpperCase()}]` : char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("");
133
+ const each = parts(base, windows).map(quote);
134
+ if (!windows) {
135
+ return `/${each.join("/+")}`;
136
+ }
137
+ return `${base.startsWith("\\\\") ? String.raw`\\\\` : ""}${each.join(String.raw`[\\/]+`)}`;
138
+ }
139
+ })(TaPathMap || (TaPathMap = {}));
35
140
 
36
141
  // web-src/migrate-frames.ts
37
142
  import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "node:crypto";
@@ -217,6 +322,211 @@ var BackupFile;
217
322
  BackupFile.readHeader = readHeader;
218
323
  })(BackupFile ||= {});
219
324
 
325
+ // web-src/migrate-paths.ts
326
+ import { open, readdir, readFile, stat } from "node:fs/promises";
327
+ import { homedir } from "node:os";
328
+ import { dirname, join } from "node:path";
329
+ var HEADER_BYTES = 64 * 1024;
330
+ var DEPTH = 4;
331
+ var MAX_FOLDERS = 20000;
332
+ var SKIPPED = new Set([
333
+ "node_modules",
334
+ "Library",
335
+ "AppData",
336
+ "Applications",
337
+ "Pictures",
338
+ "Music",
339
+ "Movies",
340
+ "Videos",
341
+ "snap",
342
+ "go",
343
+ "target",
344
+ "dist",
345
+ "build"
346
+ ]);
347
+ var MAX_PROJECTS = 500;
348
+ var MigratePaths;
349
+ ((MigratePaths) => {
350
+ async function directories(agentDir) {
351
+ const counts = new Map;
352
+ const root = join(agentDir, "sessions");
353
+ for (const dir of await readdir(root, { withFileTypes: true }).catch(() => [])) {
354
+ if (!dir.isDirectory()) {
355
+ continue;
356
+ }
357
+ for (const name of await readdir(join(root, dir.name)).catch(() => [])) {
358
+ const cwd = name.endsWith(".jsonl") ? await headerCwd(join(root, dir.name, name)) : undefined;
359
+ if (cwd) {
360
+ counts.set(cwd, (counts.get(cwd) ?? 0) + 1);
361
+ }
362
+ }
363
+ }
364
+ return counts;
365
+ }
366
+ MigratePaths.directories = directories;
367
+ async function projects(agentDir) {
368
+ const found = [];
369
+ for (const cwd of (await directories(agentDir)).keys()) {
370
+ const remote = await gitRemote(cwd);
371
+ if (remote) {
372
+ found.push({ cwd, remote });
373
+ }
374
+ if (found.length >= MAX_PROJECTS) {
375
+ break;
376
+ }
377
+ }
378
+ return found;
379
+ }
380
+ MigratePaths.projects = projects;
381
+ async function missing(agentDir, projects2 = [], map = (path) => path, home = homedir()) {
382
+ const gone = [];
383
+ for (const [cwd, conversations] of await directories(agentDir)) {
384
+ if (!await isDirectory(cwd)) {
385
+ gone.push({ dir: cwd, conversations });
386
+ }
387
+ }
388
+ gone.sort((a, b) => a.dir.length - b.dir.length);
389
+ const groups = [];
390
+ for (const each of gone) {
391
+ const parent = groups.find((group) => TaPathMap.under(each.dir, group.dir));
392
+ if (parent) {
393
+ parent.conversations += each.conversations;
394
+ } else {
395
+ groups.push({ ...each });
396
+ }
397
+ }
398
+ if (!groups.length) {
399
+ return [];
400
+ }
401
+ const remotes = new Map(projects2.map((project) => [map(project.cwd), normalizeRemote(project.remote)]));
402
+ let found;
403
+ for (const group of groups) {
404
+ const near = await homeGuess(group.dir, home);
405
+ if (near) {
406
+ group.suggestion = near;
407
+ continue;
408
+ }
409
+ found ??= await look(home, remotes.size > 0);
410
+ const remote = remotes.get(group.dir);
411
+ const byRemote = remote ? found.byRemote.get(remote) : undefined;
412
+ const byName = found.byName.get(TaPathMap.basename(group.dir).toLowerCase());
413
+ const suggestion = byRemote?.length === 1 ? byRemote[0] : byName?.length === 1 ? byName[0] : undefined;
414
+ if (suggestion) {
415
+ group.suggestion = suggestion;
416
+ }
417
+ }
418
+ return groups.sort((a, b) => b.conversations - a.conversations);
419
+ }
420
+ MigratePaths.missing = missing;
421
+ async function homeGuess(dir, home) {
422
+ const match = /^(?:[a-zA-Z]:[\\/]+(?:Users|Documents and Settings)[\\/]+[^\\/]+|\/(?:Users|home)\/[^/]+)(?=$|[\\/])/i.exec(dir);
423
+ if (!match) {
424
+ return;
425
+ }
426
+ const guess = TaPathMap.path(dir, [[match[0], home]]);
427
+ return guess !== dir && await isDirectory(guess) ? guess : undefined;
428
+ }
429
+ MigratePaths.homeGuess = homeGuess;
430
+ function normalizeRemote(url) {
431
+ return url.trim().replace(/\.git$/, "").replace(/^[a-z+]+:\/\/(?:[^@/]+@)?/i, "").replace(/^[^@/]+@([^:/]+):/, "$1/").toLowerCase();
432
+ }
433
+ MigratePaths.normalizeRemote = normalizeRemote;
434
+ async function gitRemote(cwd) {
435
+ let dir = cwd;
436
+ for (let i = 0;i < 20; i++) {
437
+ const config = await readFile(join(dir, ".git", "config"), "utf8").catch(() => {
438
+ return;
439
+ });
440
+ if (config !== undefined) {
441
+ return remoteOf(config);
442
+ }
443
+ const parent = dirname(dir);
444
+ if (parent === dir) {
445
+ return;
446
+ }
447
+ dir = parent;
448
+ }
449
+ return;
450
+ }
451
+ MigratePaths.gitRemote = gitRemote;
452
+ function remoteOf(config) {
453
+ const urls = [];
454
+ let section = "";
455
+ for (const line of config.split(/\r?\n/)) {
456
+ const head = /^\s*\[\s*remote\s+"([^"]+)"\s*\]/.exec(line);
457
+ if (head) {
458
+ section = head[1];
459
+ continue;
460
+ }
461
+ if (/^\s*\[/.test(line)) {
462
+ section = "";
463
+ continue;
464
+ }
465
+ const url = /^\s*url\s*=\s*(.+?)\s*$/.exec(line);
466
+ if (section && url) {
467
+ urls.push([section, url[1]]);
468
+ }
469
+ }
470
+ return (urls.find(([name]) => name === "origin") ?? urls[0])?.[1];
471
+ }
472
+ MigratePaths.remoteOf = remoteOf;
473
+ async function look(home, remotes) {
474
+ const found = { byName: new Map, byRemote: new Map };
475
+ let folders = 0;
476
+ const add = (map, key, path) => map.set(key, [...map.get(key) ?? [], path]);
477
+ const visit = async (dir, depth) => {
478
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
479
+ if (remotes && entries.some((entry) => entry.name === ".git")) {
480
+ const config = await readFile(join(dir, ".git", "config"), "utf8").catch(() => {
481
+ return;
482
+ });
483
+ const remote = config && remoteOf(config);
484
+ if (remote) {
485
+ add(found.byRemote, normalizeRemote(remote), dir);
486
+ }
487
+ }
488
+ for (const entry of entries) {
489
+ if (!entry.isDirectory() || entry.name.startsWith(".") || SKIPPED.has(entry.name) || ++folders > MAX_FOLDERS) {
490
+ continue;
491
+ }
492
+ const path = join(dir, entry.name);
493
+ add(found.byName, entry.name.toLowerCase(), path);
494
+ if (depth < DEPTH) {
495
+ await visit(path, depth + 1);
496
+ }
497
+ }
498
+ };
499
+ await visit(home, 1);
500
+ return found;
501
+ }
502
+ })(MigratePaths ||= {});
503
+ async function isDirectory(path) {
504
+ return (await stat(path).catch(() => {
505
+ return;
506
+ }))?.isDirectory() ?? false;
507
+ }
508
+ async function headerCwd(file) {
509
+ const handle = await open(file, "r").catch(() => {
510
+ return;
511
+ });
512
+ if (!handle) {
513
+ return;
514
+ }
515
+ try {
516
+ const buffer = Buffer.alloc(HEADER_BYTES);
517
+ const { bytesRead } = await handle.read(buffer, 0, HEADER_BYTES, 0);
518
+ const text = buffer.subarray(0, bytesRead).toString("utf8");
519
+ const end = text.indexOf(`
520
+ `);
521
+ const header = JSON.parse(end < 0 ? text : text.slice(0, end));
522
+ return header.type === "session" && typeof header.cwd === "string" ? header.cwd : undefined;
523
+ } catch {
524
+ return;
525
+ } finally {
526
+ await handle.close();
527
+ }
528
+ }
529
+
220
530
  // web-src/sync-codec.ts
221
531
  import { createHash } from "node:crypto";
222
532
  import { gunzipSync, gzipSync } from "node:zlib";
@@ -364,8 +674,8 @@ var SyncCodec;
364
674
  })(SyncCodec ||= {});
365
675
 
366
676
  // web-src/sync-items.ts
367
- import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
368
- import { dirname, join, relative, sep } from "node:path";
677
+ import { mkdir, readdir as readdir2, readFile as readFile2, rename, rm, stat as stat2, writeFile } from "node:fs/promises";
678
+ import { dirname as dirname2, join as join2, relative, sep } from "node:path";
369
679
  var SETTINGS = "settings.json";
370
680
  var SYNC_FILES = {
371
681
  "keybindings.json": "settings",
@@ -379,7 +689,7 @@ var SYNC_FILES = {
379
689
  };
380
690
  var IDENTITY_FILES = ["identity.json", "rooms.json", "friends.json"];
381
691
  var SYNC_UNITS = { skills: "skills", prompts: "skills", themes: "skills", extensions: "extensions" };
382
- var SKIPPED = new Set(["node_modules", ".git", ".DS_Store"]);
692
+ var SKIPPED2 = new Set(["node_modules", ".git", ".DS_Store"]);
383
693
  var MAX_FILE = 4 * 1024 * 1024;
384
694
  var PORTABLE = /^(npm:|git:|github:|git@|https?:\/\/)/;
385
695
  var SyncItems;
@@ -453,11 +763,11 @@ var SyncItems;
453
763
  })(SyncItems ||= {});
454
764
  async function readText(file) {
455
765
  try {
456
- const info = await stat(file);
766
+ const info = await stat2(file);
457
767
  if (!info.isFile()) {
458
768
  return;
459
769
  }
460
- return { bytes: new Uint8Array(await readFile(file)), at: info.mtimeMs };
770
+ return { bytes: new Uint8Array(await readFile2(file)), at: info.mtimeMs };
461
771
  } catch {
462
772
  return;
463
773
  }
@@ -466,19 +776,19 @@ async function walk(root) {
466
776
  const files = new Map;
467
777
  let at = 0;
468
778
  const visit = async (dir) => {
469
- for (const entry of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
470
- if (SKIPPED.has(entry.name)) {
779
+ for (const entry of await readdir2(dir, { withFileTypes: true }).catch(() => [])) {
780
+ if (SKIPPED2.has(entry.name)) {
471
781
  continue;
472
782
  }
473
- const path = join(dir, entry.name);
783
+ const path = join2(dir, entry.name);
474
784
  if (entry.isDirectory()) {
475
785
  await visit(path);
476
786
  } else if (entry.isFile()) {
477
- const info = await stat(path).catch(() => {
787
+ const info = await stat2(path).catch(() => {
478
788
  return;
479
789
  });
480
790
  if (info && info.size <= MAX_FILE) {
481
- files.set(relative(root, path).split(sep).join("/"), new Uint8Array(await readFile(path)));
791
+ files.set(relative(root, path).split(sep).join("/"), new Uint8Array(await readFile2(path)));
482
792
  at = Math.max(at, info.mtimeMs);
483
793
  }
484
794
  }
@@ -499,7 +809,7 @@ class AgentDirPlace {
499
809
  this.agentDir = agentDir;
500
810
  this.side = side;
501
811
  this.now = now;
502
- this.replacedDir = join(agentDir, "sync", "replaced");
812
+ this.replacedDir = join2(agentDir, "sync", "replaced");
503
813
  }
504
814
  begin() {
505
815
  this.stamp = undefined;
@@ -508,7 +818,7 @@ class AgentDirPlace {
508
818
  const items = new Map;
509
819
  const add = (item) => item && items.set(item.id, item);
510
820
  if (resources.has("settings") || resources.has("extensions")) {
511
- const file = await readText(join(this.agentDir, SETTINGS));
821
+ const file = await readText(join2(this.agentDir, SETTINGS));
512
822
  const parsed = file ? safeParse(file.bytes) : {};
513
823
  const settings = SyncMerge.isObject(parsed) ? parsed : undefined;
514
824
  if (settings && resources.has("settings")) {
@@ -522,7 +832,7 @@ class AgentDirPlace {
522
832
  }
523
833
  for (const [name, resource] of Object.entries(SYNC_FILES)) {
524
834
  if (resources.has(resource)) {
525
- const file = await readText(join(this.agentDir, name));
835
+ const file = await readText(join2(this.agentDir, name));
526
836
  add(file && SyncItems.item(`file:${name}`, "bytes", file.bytes, file.at));
527
837
  }
528
838
  }
@@ -577,7 +887,7 @@ class AgentDirPlace {
577
887
  return;
578
888
  }
579
889
  if (type === "tree") {
580
- if ((await stat(path).catch(() => {
890
+ if ((await stat2(path).catch(() => {
581
891
  return;
582
892
  }))?.isFile()) {
583
893
  await rm(path, { force: true });
@@ -589,7 +899,7 @@ class AgentDirPlace {
589
899
  }
590
900
  }
591
901
  async keep(id, type, content, from) {
592
- const target = join(this.folder(), `from-${from.replace(/[^\w.-]/g, "_")}`, this.asidePath(id));
902
+ const target = join2(this.folder(), `from-${from.replace(/[^\w.-]/g, "_")}`, this.asidePath(id));
593
903
  if (type === "tree") {
594
904
  await this.writeTree(target, SyncCodec.unpack(content));
595
905
  } else {
@@ -602,7 +912,7 @@ class AgentDirPlace {
602
912
  async signature(resources) {
603
913
  const parts = [];
604
914
  const note = async (path, deep) => {
605
- const info = await stat(path).catch(() => {
915
+ const info = await stat2(path).catch(() => {
606
916
  return;
607
917
  });
608
918
  if (!info) {
@@ -610,53 +920,53 @@ class AgentDirPlace {
610
920
  }
611
921
  parts.push(`${relative(this.agentDir, path)}:${info.mtimeMs}:${info.size}`);
612
922
  if (deep && info.isDirectory()) {
613
- for (const entry of await readdir(path).catch(() => [])) {
614
- if (!SKIPPED.has(entry)) {
615
- await note(join(path, entry), true);
923
+ for (const entry of await readdir2(path).catch(() => [])) {
924
+ if (!SKIPPED2.has(entry)) {
925
+ await note(join2(path, entry), true);
616
926
  }
617
927
  }
618
928
  }
619
929
  };
620
930
  if (resources.has("settings") || resources.has("extensions")) {
621
- await note(join(this.agentDir, SETTINGS), false);
931
+ await note(join2(this.agentDir, SETTINGS), false);
622
932
  }
623
933
  for (const [name, resource] of Object.entries(SYNC_FILES)) {
624
934
  if (resources.has(resource)) {
625
- await note(join(this.agentDir, name), false);
935
+ await note(join2(this.agentDir, name), false);
626
936
  }
627
937
  }
628
938
  for (const [dir, resource] of Object.entries(SYNC_UNITS)) {
629
939
  if (resources.has(resource)) {
630
- await note(join(this.agentDir, dir), true);
940
+ await note(join2(this.agentDir, dir), true);
631
941
  }
632
942
  }
633
943
  if (resources.has("identity")) {
634
944
  for (const name of IDENTITY_FILES) {
635
- await note(join(this.agentDir, name), false);
945
+ await note(join2(this.agentDir, name), false);
636
946
  }
637
947
  }
638
948
  return parts.join(`
639
949
  `);
640
950
  }
641
951
  get usedFolder() {
642
- return this.stamp ? join(this.replacedDir, this.stamp) : undefined;
952
+ return this.stamp ? join2(this.replacedDir, this.stamp) : undefined;
643
953
  }
644
954
  async keepAside(path, bytes) {
645
- await this.writeFile(join(this.folder(), ...path.split("/")), bytes);
955
+ await this.writeFile(join2(this.folder(), ...path.split("/")), bytes);
646
956
  }
647
957
  async replacedCount() {
648
- const folders = await readdir(this.replacedDir).catch(() => []);
958
+ const folders = await readdir2(this.replacedDir).catch(() => []);
649
959
  return folders.length;
650
960
  }
651
961
  async units(dir) {
652
- const root = join(this.agentDir, dir);
962
+ const root = join2(this.agentDir, dir);
653
963
  const items = [];
654
- for (const entry of await readdir(root, { withFileTypes: true }).catch(() => [])) {
655
- if (SKIPPED.has(entry.name) || entry.name.startsWith(".")) {
964
+ for (const entry of await readdir2(root, { withFileTypes: true }).catch(() => [])) {
965
+ if (SKIPPED2.has(entry.name) || entry.name.startsWith(".")) {
656
966
  continue;
657
967
  }
658
968
  const id = `${dir}/${entry.name}`;
659
- const path = join(root, entry.name);
969
+ const path = join2(root, entry.name);
660
970
  if (entry.isDirectory()) {
661
971
  const { files, at } = await walk(path);
662
972
  if (files.size) {
@@ -676,12 +986,12 @@ class AgentDirPlace {
676
986
  if (!SyncItems.resourceOf(id) || !SyncItems.safePath(path)) {
677
987
  return;
678
988
  }
679
- return join(this.agentDir, ...path.split("/"));
989
+ return join2(this.agentDir, ...path.split("/"));
680
990
  }
681
991
  asidePath(id) {
682
992
  const data = SyncItems.parseDataId(id);
683
993
  if (data) {
684
- return join("data", ...data.name.split("/"), `${data.key.replace(/[^\w.-]/g, "_")}.json`);
994
+ return join2("data", ...data.name.split("/"), `${data.key.replace(/[^\w.-]/g, "_")}.json`);
685
995
  }
686
996
  if (id === "settings" || id === "packages") {
687
997
  return `${id}.json`;
@@ -694,10 +1004,10 @@ class AgentDirPlace {
694
1004
  const pad = (value) => String(value).padStart(2, "0");
695
1005
  this.stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
696
1006
  }
697
- return join(this.replacedDir, this.stamp);
1007
+ return join2(this.replacedDir, this.stamp);
698
1008
  }
699
1009
  async asideOf(id, type) {
700
- const target = join(this.folder(), this.asidePath(id));
1010
+ const target = join2(this.folder(), this.asidePath(id));
701
1011
  if (id === "settings" || id === "packages" || id.startsWith("data:")) {
702
1012
  const current = (await this.read(new Set([SyncItems.resourceOf(id)]))).get(id);
703
1013
  if (current) {
@@ -723,7 +1033,7 @@ class AgentDirPlace {
723
1033
  }
724
1034
  async applyPackages(value) {
725
1035
  const wanted = Array.isArray(value) ? value.map((entry) => SyncItems.source(entry)).filter((entry) => !!entry) : [];
726
- const file = await readText(join(this.agentDir, SETTINGS));
1036
+ const file = await readText(join2(this.agentDir, SETTINGS));
727
1037
  const settings = file ? safeParse(file.bytes) : {};
728
1038
  const have = SyncMerge.isObject(settings) ? SyncItems.portablePackages(settings).map((entry) => SyncItems.source(entry)).filter((entry) => !!entry) : [];
729
1039
  for (const source of wanted.filter((entry) => !have.includes(entry))) {
@@ -737,17 +1047,17 @@ class AgentDirPlace {
737
1047
  const { files: before } = await walk(root);
738
1048
  for (const path of before.keys()) {
739
1049
  if (!files.has(path)) {
740
- await rm(join(root, ...path.split("/")), { force: true });
1050
+ await rm(join2(root, ...path.split("/")), { force: true });
741
1051
  }
742
1052
  }
743
1053
  for (const [path, bytes] of files) {
744
1054
  if (SyncItems.safePath(path)) {
745
- await this.writeFile(join(root, ...path.split("/")), bytes);
1055
+ await this.writeFile(join2(root, ...path.split("/")), bytes);
746
1056
  }
747
1057
  }
748
1058
  }
749
1059
  async writeFile(path, bytes) {
750
- await mkdir(dirname(path), { recursive: true });
1060
+ await mkdir(dirname2(path), { recursive: true });
751
1061
  const temporary = `${path}.ta-sync-${process.pid}`;
752
1062
  await writeFile(temporary, bytes);
753
1063
  await rename(temporary, path);
@@ -787,14 +1097,14 @@ var MAX_ENTRY = 512 * 1024 * 1024;
787
1097
  async function files(root, keep = () => true) {
788
1098
  const found = [];
789
1099
  const visit = async (dir) => {
790
- for (const entry of await readdir2(dir, { withFileTypes: true }).catch(() => [])) {
791
- const path = join2(dir, entry.name);
1100
+ for (const entry of await readdir3(dir, { withFileTypes: true }).catch(() => [])) {
1101
+ const path = join3(dir, entry.name);
792
1102
  if (entry.isDirectory()) {
793
1103
  await visit(path);
794
1104
  } else if (entry.isFile()) {
795
1105
  const rel = relative2(root, path).split(sep2).join("/");
796
1106
  if (keep(rel)) {
797
- found.push({ path: rel, size: (await stat2(path)).size });
1107
+ found.push({ path: rel, size: (await stat3(path)).size });
798
1108
  }
799
1109
  }
800
1110
  }
@@ -809,25 +1119,12 @@ var MigrateUtil;
809
1119
  }
810
1120
  MigrateUtil.sessionDir = sessionDir;
811
1121
  function remapPath(path, from, to) {
812
- if (from.agentDir && (path === from.agentDir || path.startsWith(`${from.agentDir}/`))) {
813
- return to.agentDir + path.slice(from.agentDir.length);
814
- }
815
- if (from.home && (path === from.home || path.startsWith(`${from.home}/`))) {
816
- return to.home + path.slice(from.home.length);
817
- }
818
- return path;
1122
+ return TaPathMap.path(path, [
1123
+ [from.agentDir, to.agentDir],
1124
+ [from.home, to.home]
1125
+ ]);
819
1126
  }
820
1127
  MigrateUtil.remapPath = remapPath;
821
- function remapText(text, pairs) {
822
- let out = text;
823
- for (const [before, after] of pairs) {
824
- if (before && before !== after) {
825
- out = out.split(before).join(after);
826
- }
827
- }
828
- return out;
829
- }
830
- MigrateUtil.remapText = remapText;
831
1128
  })(MigrateUtil ||= {});
832
1129
 
833
1130
  class MigrateSource {
@@ -852,9 +1149,11 @@ class MigrateSource {
852
1149
  count.bytes += head.size ?? 0;
853
1150
  bytes += head.size ?? 0;
854
1151
  }
1152
+ const projects = categories.includes("conversations") ? await MigratePaths.projects(this.agentDir) : [];
855
1153
  return {
856
1154
  v: 1,
857
- from: { name: this.name, platform: platform(), home: homedir(), agentDir: this.agentDir },
1155
+ from: { name: this.name, platform: platform(), home: homedir2(), agentDir: this.agentDir },
1156
+ ...projects.length ? { projects } : {},
858
1157
  categories: [...categories],
859
1158
  counts,
860
1159
  bytes,
@@ -873,19 +1172,19 @@ class MigrateSource {
873
1172
  async entries(categories) {
874
1173
  const wanted = new Set(categories);
875
1174
  const entries = [];
876
- const file = (c, k, path, size) => entries.push({ head: { k, c, path, size }, read: async () => new Uint8Array(await readFile2(join2(this.agentDir, ...path.split("/")))) });
1175
+ const file = (c, k, path, size) => entries.push({ head: { k, c, path, size }, read: async () => new Uint8Array(await readFile3(join3(this.agentDir, ...path.split("/")))) });
877
1176
  for (const category of ORDER.filter((each) => wanted.has(each))) {
878
1177
  if (category === "conversations") {
879
- for (const found of await files(join2(this.agentDir, "sessions"), (path) => path.endsWith(".jsonl"))) {
1178
+ for (const found of await files(join3(this.agentDir, "sessions"), (path) => path.endsWith(".jsonl"))) {
880
1179
  file(category, "file", `sessions/${found.path}`, found.size);
881
1180
  }
882
1181
  } else if (category === "changes") {
883
- for (const found of await files(join2(this.agentDir, "changes"))) {
1182
+ for (const found of await files(join3(this.agentDir, "changes"))) {
884
1183
  file(category, "file", `changes/${found.path}`, found.size);
885
1184
  }
886
1185
  } else if (category === "credentials") {
887
1186
  await this.json(entries, category, "auth.json");
888
- for (const found of await files(join2(this.agentDir, "bots"))) {
1187
+ for (const found of await files(join3(this.agentDir, "bots"))) {
889
1188
  file(category, "file", `bots/${found.path}`, found.size);
890
1189
  }
891
1190
  } else if (category === "identity") {
@@ -906,13 +1205,13 @@ class MigrateSource {
906
1205
  });
907
1206
  }
908
1207
  } else if (category === "data") {
909
- const root = join2(this.agentDir, "extension-data");
1208
+ const root = join3(this.agentDir, "extension-data");
910
1209
  for (const found of await files(root, (path) => path.endsWith(".json") && !path.startsWith("directories/"))) {
911
1210
  const name = found.path.slice(0, -".json".length);
912
1211
  if (name !== OWN) {
913
1212
  entries.push({
914
1213
  head: { k: "data", c: category, name, size: found.size },
915
- read: async () => new Uint8Array(await readFile2(join2(root, ...found.path.split("/"))))
1214
+ read: async () => new Uint8Array(await readFile3(join3(root, ...found.path.split("/"))))
916
1215
  });
917
1216
  }
918
1217
  }
@@ -946,11 +1245,11 @@ class MigrateSource {
946
1245
  await send(Frames.record({ k: "end" }));
947
1246
  }
948
1247
  async json(entries, c, path) {
949
- const info = await stat2(join2(this.agentDir, path)).catch(() => {
1248
+ const info = await stat3(join3(this.agentDir, path)).catch(() => {
950
1249
  return;
951
1250
  });
952
1251
  if (info?.isFile()) {
953
- entries.push({ head: { k: "json", c, path, size: info.size }, read: async () => new Uint8Array(await readFile2(join2(this.agentDir, path))) });
1252
+ entries.push({ head: { k: "json", c, path, size: info.size }, read: async () => new Uint8Array(await readFile3(join3(this.agentDir, path))) });
954
1253
  }
955
1254
  }
956
1255
  }
@@ -961,7 +1260,7 @@ class MigrateTarget {
961
1260
  side;
962
1261
  manifest;
963
1262
  report = { conversations: 0, keptConversations: 0, items: 0, data: 0, extensions: 0, files: 0, skipped: [] };
964
- to = { home: homedir(), agentDir: "" };
1263
+ to = { home: homedir2(), agentDir: "" };
965
1264
  sessions = new Map;
966
1265
  known;
967
1266
  locals;
@@ -998,9 +1297,10 @@ class MigrateTarget {
998
1297
  this.report.skipped.push({ id, reason: error instanceof Error ? error.message : String(error) });
999
1298
  }
1000
1299
  }
1001
- finish() {
1300
+ async finish() {
1002
1301
  const replaced = this.place.usedFolder;
1003
- return replaced ? { ...this.report, replaced } : this.report;
1302
+ const missing = this.manifest.categories.includes("conversations") ? await MigratePaths.missing(this.agentDir, this.manifest.projects, (path) => MigrateUtil.remapPath(path, this.manifest.from, this.to)).catch(() => []) : [];
1303
+ return { ...this.report, ...replaced ? { replaced } : {}, ...missing.length ? { missing } : {} };
1004
1304
  }
1005
1305
  async conversation(path, bytes) {
1006
1306
  const name = basename(path);
@@ -1026,7 +1326,7 @@ class MigrateTarget {
1026
1326
  }
1027
1327
  const cwd = MigrateUtil.remapPath(header.cwd, this.manifest.from, this.to);
1028
1328
  const rest = end < 0 ? "" : text.slice(end);
1029
- const file = join2(this.agentDir, "sessions", MigrateUtil.sessionDir(cwd), name);
1329
+ const file = join3(this.agentDir, "sessions", MigrateUtil.sessionDir(cwd), name);
1030
1330
  await this.write(file, new TextEncoder().encode(JSON.stringify({ ...header, cwd }) + rest));
1031
1331
  known.set(name, file);
1032
1332
  this.sessions.set(from, file);
@@ -1037,8 +1337,8 @@ class MigrateTarget {
1037
1337
  if (!SyncItems.safePath(path) || !/^(changes|bots)\//.test(path)) {
1038
1338
  throw new Error("Not a file Ta moves.");
1039
1339
  }
1040
- const target = join2(this.agentDir, ...path.split("/"));
1041
- const before = await readFile2(target).catch(() => {
1340
+ const target = join3(this.agentDir, ...path.split("/"));
1341
+ const before = await readFile3(target).catch(() => {
1042
1342
  return;
1043
1343
  });
1044
1344
  if (before && Buffer.from(bytes).equals(before)) {
@@ -1057,11 +1357,12 @@ class MigrateTarget {
1057
1357
  if (path !== "auth.json" && path !== "ta.json") {
1058
1358
  throw new Error("Not a file Ta moves.");
1059
1359
  }
1060
- const target = join2(this.agentDir, path);
1061
- const before = await readFile2(target).catch(() => {
1360
+ const target = join3(this.agentDir, path);
1361
+ const before = await readFile3(target).catch(() => {
1062
1362
  return;
1063
1363
  });
1064
- const remote = JSON.parse(path === "ta.json" ? this.remap(new TextDecoder().decode(bytes)) : new TextDecoder().decode(bytes));
1364
+ const read = JSON.parse(new TextDecoder().decode(bytes));
1365
+ const remote = path === "ta.json" ? this.remap(read) : read;
1065
1366
  const local = before ? JSON.parse(before.toString("utf8")) : {};
1066
1367
  const merged = SyncMerge.value(undefined, local, remote);
1067
1368
  if (SyncMerge.same(merged, local)) {
@@ -1120,7 +1421,7 @@ class MigrateTarget {
1120
1421
  if (name === OWN) {
1121
1422
  return;
1122
1423
  }
1123
- const data = JSON.parse(this.remap(new TextDecoder().decode(bytes)));
1424
+ const data = this.remap(JSON.parse(new TextDecoder().decode(bytes)));
1124
1425
  if (!SyncMerge.isObject(data)) {
1125
1426
  throw new Error("Not the data of a package.");
1126
1427
  }
@@ -1132,7 +1433,7 @@ class MigrateTarget {
1132
1433
  }
1133
1434
  if (local !== undefined && !this.asideData.has(name)) {
1134
1435
  this.asideData.add(name);
1135
- const file = await readFile2(join2(this.agentDir, "extension-data", ...`${name}.json`.split("/"))).catch(() => {
1436
+ const file = await readFile3(join3(this.agentDir, "extension-data", ...`${name}.json`.split("/"))).catch(() => {
1136
1437
  return;
1137
1438
  });
1138
1439
  if (file) {
@@ -1146,24 +1447,22 @@ class MigrateTarget {
1146
1447
  this.report.data++;
1147
1448
  }
1148
1449
  }
1149
- remap(text) {
1150
- const pairs = [...this.sessions];
1151
- pairs.push([this.manifest.from.agentDir, this.to.agentDir], [`${this.manifest.from.home}/`, `${this.to.home}/`]);
1152
- return MigrateUtil.remapText(text, pairs);
1450
+ remap(value) {
1451
+ return TaPathMap.json(value, [...this.sessions, [this.manifest.from.agentDir, this.to.agentDir], [this.manifest.from.home, this.to.home]]);
1153
1452
  }
1154
1453
  async knownSessions() {
1155
1454
  if (!this.known) {
1156
1455
  const known = new Map;
1157
- const root = join2(this.agentDir, "sessions");
1456
+ const root = join3(this.agentDir, "sessions");
1158
1457
  for (const found of await files(root, (path) => path.endsWith(".jsonl"))) {
1159
- known.set(basename(found.path), join2(root, ...found.path.split("/")));
1458
+ known.set(basename(found.path), join3(root, ...found.path.split("/")));
1160
1459
  }
1161
1460
  this.known = known;
1162
1461
  }
1163
1462
  return this.known;
1164
1463
  }
1165
1464
  async write(file, bytes, mode) {
1166
- await mkdir2(dirname2(file), { recursive: true });
1465
+ await mkdir2(dirname3(file), { recursive: true });
1167
1466
  const temporary = `${file}.ta-move-${process.pid}`;
1168
1467
  await writeFile2(temporary, bytes, mode === undefined ? undefined : { mode });
1169
1468
  await rename2(temporary, file);
@@ -1523,6 +1822,15 @@ var MigrateServerTexts;
1523
1822
  });
1524
1823
  }
1525
1824
  MigrateServerTexts.newer = newer;
1825
+ function updateThis() {
1826
+ return TaLanguageUtil.say({
1827
+ "zh-CN": "这台电脑上的 Ta 太旧,先升级 Ta。",
1828
+ "zh-TW": "這台電腦上的 Ta 太舊,先升級 Ta。",
1829
+ "en-US": "Ta here is too old for this: update it first.",
1830
+ "ja-JP": "このコンピューターの Ta が古すぎます。最初に Ta をアップデートしてください。"
1831
+ });
1832
+ }
1833
+ MigrateServerTexts.updateThis = updateThis;
1526
1834
  function cut() {
1527
1835
  return TaLanguageUtil.say({
1528
1836
  "zh-CN": "传输中断了,没有完成的部分可以重新迁移。",
@@ -1691,15 +1999,34 @@ class MigrateService {
1691
1999
  this.importing(path, password || undefined);
1692
2000
  return this.status();
1693
2001
  }
2002
+ async missing() {
2003
+ const report = this.in?.report;
2004
+ if (report?.missing) {
2005
+ return report.missing;
2006
+ }
2007
+ return MigratePaths.missing(this.options.agentDir);
2008
+ }
2009
+ async relocate(from, to) {
2010
+ if (!this.options.relocate) {
2011
+ throw new Error(MigrateServerTexts.updateThis());
2012
+ }
2013
+ const result = await this.options.relocate(from, to);
2014
+ const report = this.in?.report;
2015
+ if (report?.missing) {
2016
+ report.missing = report.missing.filter((each) => each.dir !== from);
2017
+ this.publish(true);
2018
+ }
2019
+ return result;
2020
+ }
1694
2021
  async listBackups() {
1695
2022
  const found = [];
1696
2023
  for (const dir of this.backupDirs()) {
1697
- for (const name of await readdir3(dir).catch(() => [])) {
2024
+ for (const name of await readdir4(dir).catch(() => [])) {
1698
2025
  if (!name.endsWith(BACKUP_EXTENSION)) {
1699
2026
  continue;
1700
2027
  }
1701
- const path = join3(dir, name);
1702
- const info = await stat3(path).catch(() => {
2028
+ const path = join4(dir, name);
2029
+ const info = await stat4(path).catch(() => {
1703
2030
  return;
1704
2031
  });
1705
2032
  if (info?.isFile()) {
@@ -1733,7 +2060,7 @@ class MigrateService {
1733
2060
  return chosen;
1734
2061
  }
1735
2062
  backupDirs() {
1736
- return this.options.backupDirs ?? [join3(homedir2(), "Downloads"), join3(homedir2(), "Desktop"), homedir2()];
2063
+ return this.options.backupDirs ?? [join4(homedir3(), "Downloads"), join4(homedir3(), "Desktop"), homedir3()];
1737
2064
  }
1738
2065
  async accepted(socket, key, categories) {
1739
2066
  const out = this.out;
@@ -1822,8 +2149,8 @@ class MigrateService {
1822
2149
  if (first.t !== "manifest" || !first.manifest) {
1823
2150
  throw new Error(MigrateServerTexts.refused(into.from ?? ""));
1824
2151
  }
1825
- const open = channel;
1826
- await this.take(first.manifest, () => open.reader.next(), into);
2152
+ const open2 = channel;
2153
+ await this.take(first.manifest, () => open2.reader.next(), into);
1827
2154
  await channel.send(Frames.record({ t: "done" })).catch(() => {
1828
2155
  return;
1829
2156
  });
@@ -1876,7 +2203,7 @@ class MigrateService {
1876
2203
  }
1877
2204
  await target.apply(head, bytes);
1878
2205
  }
1879
- into.report = target.finish();
2206
+ into.report = await target.finish();
1880
2207
  into.state = "done";
1881
2208
  }
1882
2209
  async exporting(categories, password, dir) {
@@ -1885,7 +2212,7 @@ class MigrateService {
1885
2212
  const date = new Date;
1886
2213
  const pad = (value) => String(value).padStart(2, "0");
1887
2214
  const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
1888
- const path = join3(folder, `Ta-${this.name.replace(/[^\w.-]/g, "_")}-${stamp}${BACKUP_EXTENSION}`);
2215
+ const path = join4(folder, `Ta-${this.name.replace(/[^\w.-]/g, "_")}-${stamp}${BACKUP_EXTENSION}`);
1889
2216
  let stream;
1890
2217
  try {
1891
2218
  await mkdir3(folder, { recursive: true });
@@ -2107,19 +2434,34 @@ var SyncDeclarations;
2107
2434
  })(SyncDeclarations ||= {});
2108
2435
 
2109
2436
  // web-src/sync-service.ts
2110
- import { mkdir as mkdir5, readFile as readFile4, rename as rename5, rm as rm4, writeFile as writeFile4 } from "node:fs/promises";
2111
- import { hostname as hostname3, platform as platform2 } from "node:os";
2112
- import { join as join6 } from "node:path";
2437
+ import { rm as rm4 } from "node:fs/promises";
2113
2438
 
2114
2439
  // ../ta-relay/esm/node/relays-file.js
2115
2440
  import { accessSync, chmodSync, constants, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2116
- import { homedir as homedir3 } from "node:os";
2117
- import { dirname as dirname3, isAbsolute, join as join4, resolve } from "node:path";
2441
+ import { homedir as homedir4 } from "node:os";
2442
+ import { dirname as dirname4, isAbsolute, join as join5, resolve } from "node:path";
2118
2443
 
2119
2444
  // ../ta-relay/esm/common/relay-protocol.js
2120
2445
  var RELAY_DEFAULT_URL = "https://relay.cellbang.com";
2446
+ function relayDefaultUrl(env) {
2447
+ var _a, _b;
2448
+ if (env === undefined) {
2449
+ env = (_a = globalThis.process) === null || _a === undefined ? undefined : _a.env;
2450
+ }
2451
+ return ((_b = env === null || env === undefined ? undefined : env.TA_RELAY_URL) === null || _b === undefined ? undefined : _b.trim().replace(/\/+$/, "")) || RELAY_DEFAULT_URL;
2452
+ }
2121
2453
  var RELAY_FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' https: data: blob:; style-src 'unsafe-inline' https: data:; img-src https: data: blob:; font-src https: data:; media-src https: data: blob:; connect-src 'none'; form-action 'none'";
2122
2454
  var RELAY_FRAME_HEADER_CSP = `${RELAY_FRAME_CSP}; frame-ancestors 'self'; sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox`;
2455
+ var OPEN_IN_TA = `<p><a id="open" style="display:inline-block;padding:10px 18px;border-radius:20px;background:#111;color:#fff;text-decoration:none;font-weight:600">Open in Ta · 在 Ta 中打开</a></p>
2456
+ <script>document.getElementById('open').href='ta://open?link='+encodeURIComponent(location.href)</script>`;
2457
+ var RELAY_PAIR_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
2458
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
2459
+ <h1>Ta</h1><p>Open this link in the Ta app, or paste it there, to reach your Ta from this device.</p>
2460
+ <p>打开 Ta 应用,粘贴这个链接,就能从这台设备连到你的 Ta。</p>${OPEN_IN_TA}</body>`;
2461
+ var RELAY_SHARE_PAGE = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Ta</title>
2462
+ <body style="font:16px system-ui;max-width:32em;margin:3em auto;padding:0 1em">
2463
+ <h1>Ta</h1><p>Someone shared an extension of Ta. Scan the code in the Ta app, or paste this link in its Quick open, to open it.</p>
2464
+ <p>有人分享了一个 Ta 扩展。在 Ta 应用里扫码,或把这个链接粘贴到“快捷打开”,就能打开它。</p>${OPEN_IN_TA}</body>`;
2123
2465
  var RELAY_SHARE_MAX_BYTES = 8 * 1024 * 1024;
2124
2466
  var RELAY_SHARE_CHUNK_BYTES = 192 * 1024;
2125
2467
  var RELAY_CONTENT_MAX_BYTES = 8 * 1024 * 1024;
@@ -2255,13 +2597,13 @@ var RelayServiceUtil;
2255
2597
  function expand(path) {
2256
2598
  const text = String(path !== null && path !== undefined ? path : "").trim();
2257
2599
  if (text === "~" || text.startsWith("~/")) {
2258
- return join4(homedir3(), text.slice(1));
2600
+ return join5(homedir4(), text.slice(1));
2259
2601
  }
2260
- return isAbsolute(text) ? resolve(text) : resolve(homedir3(), text);
2602
+ return isAbsolute(text) ? resolve(text) : resolve(homedir4(), text);
2261
2603
  }
2262
2604
  RelayServiceUtil2.expand = expand;
2263
2605
  function portable(path) {
2264
- const home = homedir3();
2606
+ const home = homedir4();
2265
2607
  return path === home ? "~" : path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
2266
2608
  }
2267
2609
  RelayServiceUtil2.portable = portable;
@@ -2288,23 +2630,23 @@ var RelayServiceUtil;
2288
2630
  }
2289
2631
  RelayServiceUtil2.only = only;
2290
2632
  function drives() {
2291
- const home = homedir3();
2633
+ const home = homedir4();
2292
2634
  const found = [];
2293
2635
  const add = (name, dir) => {
2294
2636
  try {
2295
2637
  if (statSync(dir).isDirectory()) {
2296
- found.push({ name, path: portable(join4(dir, "Ta")) });
2638
+ found.push({ name, path: portable(join5(dir, "Ta")) });
2297
2639
  }
2298
2640
  } catch (_a) {}
2299
2641
  };
2300
- add("iCloud Drive", join4(home, "Library", "Mobile Documents", "com~apple~CloudDocs"));
2642
+ add("iCloud Drive", join5(home, "Library", "Mobile Documents", "com~apple~CloudDocs"));
2301
2643
  try {
2302
- for (const entry of readdirSync(join4(home, "Library", "CloudStorage"))) {
2303
- add(entry.replace(/-.*$/, ""), join4(home, "Library", "CloudStorage", entry));
2644
+ for (const entry of readdirSync(join5(home, "Library", "CloudStorage"))) {
2645
+ add(entry.replace(/-.*$/, ""), join5(home, "Library", "CloudStorage", entry));
2304
2646
  }
2305
2647
  } catch (_a) {}
2306
2648
  for (const name of ["Dropbox", "OneDrive", "Nutstore Files", "坚果云"]) {
2307
- add(name, join4(home, name));
2649
+ add(name, join5(home, name));
2308
2650
  }
2309
2651
  return found.filter((drive, index) => found.findIndex((other) => other.path === drive.path) === index);
2310
2652
  }
@@ -2334,7 +2676,7 @@ class RelaysFile {
2334
2676
  this.agentDir = agentDir;
2335
2677
  }
2336
2678
  get file() {
2337
- return join4(this.agentDir, RelaysFile.FILE);
2679
+ return join5(this.agentDir, RelaysFile.FILE);
2338
2680
  }
2339
2681
  read() {
2340
2682
  let text;
@@ -2365,7 +2707,7 @@ class RelaysFile {
2365
2707
  const entries = [];
2366
2708
  const own = config.relays && typeof config.relays === "object" ? config.relays : {};
2367
2709
  if (!own[OFFICIAL_RELAY]) {
2368
- entries.push({ id: OFFICIAL_RELAY, type: "ta-relay", url: RELAY_DEFAULT_URL, name: "relay.cellbang.com", builtin: true });
2710
+ entries.push({ id: OFFICIAL_RELAY, type: "ta-relay", url: relayDefaultUrl(), name: new URL(relayDefaultUrl()).host, builtin: true });
2369
2711
  }
2370
2712
  for (const [id, service] of Object.entries(own)) {
2371
2713
  if (!ID.test(id) || !service || typeof service !== "object") {
@@ -2398,7 +2740,7 @@ class RelaysFile {
2398
2740
  if (service) {
2399
2741
  return service;
2400
2742
  }
2401
- const url = fallback !== null && fallback !== undefined ? fallback : RELAY_DEFAULT_URL;
2743
+ const url = fallback !== null && fallback !== undefined ? fallback : relayDefaultUrl();
2402
2744
  return (_a = this.services(config).find((entry) => RelayServiceUtil.isRelay(entry) && entry.url === url)) !== null && _a !== undefined ? _a : { id: "", type: "ta-relay", url, builtin: false };
2403
2745
  }
2404
2746
  idFor(feature, config = this.safeRead().config) {
@@ -2411,7 +2753,7 @@ class RelaysFile {
2411
2753
  }
2412
2754
  urlFor(feature, fallback) {
2413
2755
  const service = this.serviceFor(feature, fallback);
2414
- return RelayServiceUtil.isRelay(service) ? service.url : fallback !== null && fallback !== undefined ? fallback : RELAY_DEFAULT_URL;
2756
+ return RelayServiceUtil.isRelay(service) ? service.url : fallback !== null && fallback !== undefined ? fallback : relayDefaultUrl();
2415
2757
  }
2416
2758
  add(url, name) {
2417
2759
  var _a;
@@ -2496,6 +2838,52 @@ class RelaysFile {
2496
2838
  delete relays[id];
2497
2839
  this.write({ ...config, relays });
2498
2840
  }
2841
+ join(url, deployment) {
2842
+ var _a, _b;
2843
+ const relay = deployment.relay ? this.add(deployment.relay, deployment.name) : undefined;
2844
+ const config = this.read();
2845
+ const name = (_a = deployment.name) === null || _a === undefined ? undefined : _a.trim().slice(0, 80);
2846
+ const joined = {
2847
+ url,
2848
+ ...name ? { name } : {},
2849
+ ...deployment.gateway ? { gateway: deployment.gateway } : {},
2850
+ ...relay ? { relay } : {}
2851
+ };
2852
+ const { default: before, ...rest } = config;
2853
+ const fallback = relay !== null && relay !== undefined ? relay : before === ((_b = config.deployment) === null || _b === undefined ? undefined : _b.relay) ? undefined : before;
2854
+ this.write({ ...rest, ...fallback ? { default: fallback } : {}, deployment: joined });
2855
+ return joined;
2856
+ }
2857
+ leave() {
2858
+ var _a, _b;
2859
+ const config = this.read();
2860
+ const joined = config.deployment;
2861
+ if (!joined) {
2862
+ return;
2863
+ }
2864
+ const { deployment: _left, default: before, ...rest } = config;
2865
+ const relays = { ...(_a = rest.relays) !== null && _a !== undefined ? _a : {} };
2866
+ const used = Object.values((_b = rest.use) !== null && _b !== undefined ? _b : {});
2867
+ if (joined.relay && joined.relay !== OFFICIAL_RELAY && !used.includes(joined.relay)) {
2868
+ delete relays[joined.relay];
2869
+ }
2870
+ const kept = before && before !== joined.relay ? before : undefined;
2871
+ this.write({ ...rest, relays, ...kept ? { default: kept } : {} });
2872
+ }
2873
+ deployment(config = this.safeRead().config) {
2874
+ const joined = config.deployment;
2875
+ if (!joined || typeof joined !== "object" || typeof joined.url !== "string") {
2876
+ return;
2877
+ }
2878
+ const text = (value) => typeof value === "string" && value ? value : undefined;
2879
+ const relay = text(joined.relay);
2880
+ return {
2881
+ url: joined.url,
2882
+ ...text(joined.name) ? { name: text(joined.name) } : {},
2883
+ ...text(joined.gateway) ? { gateway: text(joined.gateway) } : {},
2884
+ ...relay && this.services(config).some((service) => service.id === relay) ? { relay } : {}
2885
+ };
2886
+ }
2499
2887
  use(feature, id) {
2500
2888
  var _a;
2501
2889
  const config = this.read();
@@ -2518,7 +2906,7 @@ class RelaysFile {
2518
2906
  this.write({ ...config, use });
2519
2907
  }
2520
2908
  write(config) {
2521
- mkdirSync(dirname3(this.file), { recursive: true });
2909
+ mkdirSync(dirname4(this.file), { recursive: true });
2522
2910
  const temporary = `${this.file}.${process.pid}.tmp`;
2523
2911
  writeFileSync(temporary, `${JSON.stringify(config, null, 2)}
2524
2912
  `, { mode: 384 });
@@ -2538,290 +2926,116 @@ class RelaysFile {
2538
2926
  }
2539
2927
  RelaysFile.FILE = "relays.json";
2540
2928
 
2541
- // web-src/sync-engine.ts
2542
- var ATTEMPTS = 3;
2543
- var TOMBSTONE_MS = 90 * 24 * 60 * 60 * 1000;
2544
-
2545
- class SyncEngine {
2546
- room;
2547
- place;
2548
- device;
2549
- now;
2550
- constructor(room, place, device, now = Date.now) {
2551
- this.room = room;
2552
- this.place = place;
2553
- this.device = device;
2554
- this.now = now;
2929
+ // web-src/sync-folder.ts
2930
+ import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHmac, randomBytes as randomBytes4 } from "node:crypto";
2931
+ import { watch } from "node:fs";
2932
+ import { mkdir as mkdir4, readdir as readdir5, readFile as readFile4, rename as rename4, rm as rm3, stat as stat5, writeFile as writeFile3 } from "node:fs/promises";
2933
+ import { join as join6, sep as sep3 } from "node:path";
2934
+ var CHECK = "ta-sync folder v1";
2935
+ var DIR = "ta-sync";
2936
+ var FOLDER_PIECE = 4 * 1024 * 1024;
2937
+ var FolderSyncUtil;
2938
+ ((FolderSyncUtil) => {
2939
+ function randomId() {
2940
+ return randomBytes4(16).toString("base64url");
2555
2941
  }
2556
- async round(base, resources) {
2557
- const report = { at: this.now(), sent: 0, received: 0, skipped: [] };
2558
- for (let attempt = 0;attempt < ATTEMPTS; attempt++) {
2559
- const raced = await this.once(base, resources, report);
2560
- if (!raced) {
2561
- break;
2562
- }
2942
+ FolderSyncUtil.randomId = randomId;
2943
+ function randomKey() {
2944
+ return randomBytes4(32).toString("base64url");
2945
+ }
2946
+ FolderSyncUtil.randomKey = randomKey;
2947
+ function link(record, name) {
2948
+ const fragment = new URLSearchParams({ v: "1", s: record.id, k: record.key, p: record.path, n: name });
2949
+ return `ta-sync://folder#${fragment}`;
2950
+ }
2951
+ FolderSyncUtil.link = link;
2952
+ function storeLink(record, config, name) {
2953
+ const options = Buffer.from(JSON.stringify(config.options)).toString("base64url");
2954
+ const fragment = new URLSearchParams({
2955
+ v: "1",
2956
+ s: record.id,
2957
+ k: record.key,
2958
+ t: config.type,
2959
+ o: options,
2960
+ ...config.name ? { a: config.name } : {},
2961
+ n: name
2962
+ });
2963
+ return `ta-sync://store#${fragment}`;
2964
+ }
2965
+ FolderSyncUtil.storeLink = storeLink;
2966
+ function isStore(text) {
2967
+ return String(text ?? "").trim().startsWith("ta-sync://store#");
2968
+ }
2969
+ FolderSyncUtil.isStore = isStore;
2970
+ function parseStore(text) {
2971
+ const value = String(text ?? "").trim();
2972
+ const fragment = new URLSearchParams(value.slice(value.indexOf("#") + 1));
2973
+ const [id, key, type] = ["s", "k", "t"].map((name) => fragment.get(name) ?? "");
2974
+ let options;
2975
+ try {
2976
+ options = JSON.parse(Buffer.from(fragment.get("o") ?? "", "base64url").toString("utf8"));
2977
+ } catch {
2978
+ options = undefined;
2563
2979
  }
2564
- await this.dropOldMarks();
2565
- return report;
2980
+ if (!isStore(value) || fragment.get("v") !== "1" || !/^[A-Za-z0-9_-]{16,64}$/.test(id) || !/^[A-Za-z0-9_-]{43}$/.test(key) || !/^[a-z][a-z0-9-]{1,31}$/.test(type) || !options || typeof options !== "object" || Array.isArray(options)) {
2981
+ throw new Error("This is not a link of sync in a storage.");
2982
+ }
2983
+ return { id, key, type, options, service: fragment.get("a") ?? "", name: fragment.get("n") ?? "" };
2566
2984
  }
2567
- async once(base, resources, report) {
2568
- const remote = await this.remote();
2569
- const local = await this.place.read(resources);
2570
- const ids = new Set([...local.keys(), ...remote.keys(), ...Object.keys(base.items)]);
2571
- let raced = false;
2572
- for (const id of [...ids].sort()) {
2573
- const resource = SyncItems.resourceOf(id);
2574
- if (!resource || !resources.has(resource)) {
2985
+ FolderSyncUtil.parseStore = parseStore;
2986
+ function is(text) {
2987
+ return String(text ?? "").trim().startsWith("ta-sync://folder#");
2988
+ }
2989
+ FolderSyncUtil.is = is;
2990
+ function parse(text) {
2991
+ const value = String(text ?? "").trim();
2992
+ const fragment = new URLSearchParams(value.slice(value.indexOf("#") + 1));
2993
+ const [id, key, path] = ["s", "k", "p"].map((name) => fragment.get(name) ?? "");
2994
+ if (!is(value) || fragment.get("v") !== "1" || !/^[A-Za-z0-9_-]{16,64}$/.test(id) || !/^[A-Za-z0-9_-]{43}$/.test(key) || !path) {
2995
+ throw new Error("This is not a link of sync in a folder.");
2996
+ }
2997
+ return { id, key, path, name: fragment.get("n") ?? "" };
2998
+ }
2999
+ FolderSyncUtil.parse = parse;
3000
+ })(FolderSyncUtil ||= {});
3001
+
3002
+ class LocalFolderStore {
3003
+ root;
3004
+ constructor(root) {
3005
+ this.root = root;
3006
+ }
3007
+ async list(dir) {
3008
+ const found = [];
3009
+ const at = join6(this.root, ...dir.split("/").filter(Boolean));
3010
+ for (const entry of await readdir5(at, { withFileTypes: true }).catch(() => [])) {
3011
+ if (entry.name.startsWith(".")) {
2575
3012
  continue;
2576
3013
  }
2577
- try {
2578
- raced = await this.item(id, local.get(id), remote.get(id), base, report) || raced;
2579
- } catch (error) {
2580
- report.skipped.push({ id, reason: error instanceof Error ? error.message : String(error) });
2581
- }
2582
- }
2583
- return raced;
2584
- }
2585
- async item(id, local, remote, base, report) {
2586
- const type = local?.type ?? remote?.entry.t ?? "bytes";
2587
- const mergeable = type === "json" || type === "set";
2588
- const had = base.items[id];
2589
- const action = SyncMerge.decide(local, remote?.entry, had?.h, mergeable && (local?.type ?? type) === (remote?.entry.t ?? type));
2590
- switch (action) {
2591
- case "none":
2592
- base.items[id] = { h: local?.h ?? "", ...local?.value === undefined ? {} : { v: local.value } };
2593
- return false;
2594
- case "forget":
2595
- delete base.items[id];
2596
- return false;
2597
- case "push":
2598
- case "keepLocal": {
2599
- if (action === "keepLocal" && remote) {
2600
- const theirs = await this.content(remote.entry);
2601
- if (theirs) {
2602
- await this.place.keep(id, remote.entry.t, theirs, remote.entry.by);
2603
- }
2604
- }
2605
- const ok = await this.send(id, local, remote);
2606
- if (ok) {
2607
- base.items[id] = { h: local?.h ?? "", ...local?.value === undefined ? {} : { v: local.value } };
2608
- report.sent++;
2609
- }
2610
- return !ok;
2611
- }
2612
- case "pull":
2613
- case "keepRemote": {
2614
- const entry = remote?.entry;
2615
- const content = entry && !entry.deleted ? await this.content(entry) : undefined;
2616
- if (entry && !entry.deleted && !content) {
2617
- return false;
2618
- }
2619
- const aside = !!local && (action === "keepRemote" || had === undefined || local.h !== had.h);
2620
- await this.place.apply(id, entry?.t ?? type, content, aside);
2621
- base.items[id] = { h: content ? entry?.h ?? "" : "", ...content && mergeable ? { v: SyncCodec.parse(content) } : {} };
2622
- if (local || content) {
2623
- report.received++;
2624
- }
2625
- return false;
2626
- }
2627
- case "merge":
2628
- return this.merge(id, local, remote, had, base, report);
2629
- }
2630
- }
2631
- async merge(id, local, remote, had, base, report) {
2632
- const content = await this.content(remote.entry);
2633
- if (!content) {
2634
- return false;
2635
- }
2636
- const theirs = SyncCodec.parse(content);
2637
- const merged = local.type === "set" ? SyncMerge.set(Array.isArray(had?.v) ? had.v : undefined, Array.isArray(local.value) ? local.value : [], Array.isArray(theirs) ? theirs : []) : SyncMerge.value(had?.v, local.value, theirs);
2638
- const item = SyncItems.item(id, local.type, SyncCodec.json(merged), this.now(), merged);
2639
- if (item.h !== remote.entry.h && !await this.send(id, item, remote)) {
2640
- return true;
2641
- }
2642
- if (item.h !== local.h) {
2643
- await this.place.apply(id, local.type, item.bytes, false);
2644
- report.received++;
2645
- }
2646
- if (item.h !== remote.entry.h) {
2647
- report.sent++;
2648
- }
2649
- base.items[id] = { h: item.h, v: merged };
2650
- return false;
2651
- }
2652
- async send(id, local, remote) {
2653
- const entry = local ? { t: local.type, h: local.h, at: Math.round(local.at || this.now()), by: this.device, n: 0 } : { t: remote?.entry.t ?? "bytes", h: "", at: this.now(), by: this.device, n: 0, deleted: true };
2654
- if (local) {
2655
- const pieces = SyncCodec.encode(local.bytes, this.room.piece);
2656
- entry.n = pieces.length;
2657
- const there = await this.room.getState(`${SyncStateKeys.BLOB}${local.h}:`);
2658
- for (const [index, piece] of pieces.entries()) {
2659
- const key = SyncStateKeys.blob(local.h, index);
2660
- if (there[key]?.value !== piece) {
2661
- await this.room.setState(key, piece);
2662
- }
2663
- }
2664
- }
2665
- const result = await this.room.setState(SyncStateKeys.item(id), entry, remote?.version ?? 0);
2666
- if (result.ok && remote && !remote.entry.deleted && remote.entry.h !== entry.h) {
2667
- await this.dropBlob(remote.entry);
2668
- }
2669
- return result.ok;
2670
- }
2671
- async dropBlob(entry) {
2672
- const remote = await this.remote();
2673
- if ([...remote.values()].some(({ entry: other }) => !other.deleted && other.h === entry.h)) {
2674
- return;
2675
- }
2676
- for (let index = 0;index < entry.n; index++) {
2677
- await this.room.setState(SyncStateKeys.blob(entry.h, index), null);
2678
- }
2679
- }
2680
- async content(entry) {
2681
- const state = await this.room.getState(`${SyncStateKeys.BLOB}${entry.h}:`);
2682
- const pieces = [];
2683
- for (let index = 0;index < entry.n; index++) {
2684
- const piece = state[SyncStateKeys.blob(entry.h, index)]?.value;
2685
- if (typeof piece !== "string") {
2686
- return;
2687
- }
2688
- pieces.push(piece);
2689
- }
2690
- const bytes = SyncCodec.decode(pieces);
2691
- return SyncCodec.hash(bytes) === entry.h ? bytes : undefined;
2692
- }
2693
- async remote() {
2694
- const items = new Map;
2695
- for (const [key, { value, version }] of Object.entries(await this.room.getState(SyncStateKeys.ITEM))) {
2696
- if (isEntry(value)) {
2697
- items.set(key.slice(SyncStateKeys.ITEM.length), { entry: value, version });
2698
- }
2699
- }
2700
- return items;
2701
- }
2702
- async dropOldMarks() {
2703
- for (const [id, { entry, version }] of await this.remote()) {
2704
- if (entry.deleted && this.now() - entry.at > TOMBSTONE_MS) {
2705
- await this.room.setState(SyncStateKeys.item(id), null, version);
2706
- }
2707
- }
2708
- }
2709
- }
2710
- function isEntry(value) {
2711
- const entry = value;
2712
- return SyncMerge.isObject(value) && ["json", "set", "bytes", "tree"].includes(entry.t) && typeof entry.h === "string" && typeof entry.at === "number" && typeof entry.n === "number" && typeof entry.by === "string";
2713
- }
2714
-
2715
- // web-src/sync-folder.ts
2716
- import { createCipheriv as createCipheriv2, createDecipheriv as createDecipheriv2, createHmac, randomBytes as randomBytes4 } from "node:crypto";
2717
- import { watch } from "node:fs";
2718
- import { mkdir as mkdir4, readdir as readdir4, readFile as readFile3, rename as rename4, rm as rm3, stat as stat4, writeFile as writeFile3 } from "node:fs/promises";
2719
- import { join as join5, sep as sep3 } from "node:path";
2720
- var CHECK = "ta-sync folder v1";
2721
- var DIR = "ta-sync";
2722
- var FOLDER_PIECE = 4 * 1024 * 1024;
2723
- var FolderSyncUtil;
2724
- ((FolderSyncUtil) => {
2725
- function randomId() {
2726
- return randomBytes4(16).toString("base64url");
2727
- }
2728
- FolderSyncUtil.randomId = randomId;
2729
- function randomKey() {
2730
- return randomBytes4(32).toString("base64url");
2731
- }
2732
- FolderSyncUtil.randomKey = randomKey;
2733
- function link(record, name) {
2734
- const fragment = new URLSearchParams({ v: "1", s: record.id, k: record.key, p: record.path, n: name });
2735
- return `ta-sync://folder#${fragment}`;
2736
- }
2737
- FolderSyncUtil.link = link;
2738
- function storeLink(record, config, name) {
2739
- const options = Buffer.from(JSON.stringify(config.options)).toString("base64url");
2740
- const fragment = new URLSearchParams({
2741
- v: "1",
2742
- s: record.id,
2743
- k: record.key,
2744
- t: config.type,
2745
- o: options,
2746
- ...config.name ? { a: config.name } : {},
2747
- n: name
2748
- });
2749
- return `ta-sync://store#${fragment}`;
2750
- }
2751
- FolderSyncUtil.storeLink = storeLink;
2752
- function isStore(text) {
2753
- return String(text ?? "").trim().startsWith("ta-sync://store#");
2754
- }
2755
- FolderSyncUtil.isStore = isStore;
2756
- function parseStore(text) {
2757
- const value = String(text ?? "").trim();
2758
- const fragment = new URLSearchParams(value.slice(value.indexOf("#") + 1));
2759
- const [id, key, type] = ["s", "k", "t"].map((name) => fragment.get(name) ?? "");
2760
- let options;
2761
- try {
2762
- options = JSON.parse(Buffer.from(fragment.get("o") ?? "", "base64url").toString("utf8"));
2763
- } catch {
2764
- options = undefined;
2765
- }
2766
- if (!isStore(value) || fragment.get("v") !== "1" || !/^[A-Za-z0-9_-]{16,64}$/.test(id) || !/^[A-Za-z0-9_-]{43}$/.test(key) || !/^[a-z][a-z0-9-]{1,31}$/.test(type) || !options || typeof options !== "object" || Array.isArray(options)) {
2767
- throw new Error("This is not a link of sync in a storage.");
2768
- }
2769
- return { id, key, type, options, service: fragment.get("a") ?? "", name: fragment.get("n") ?? "" };
2770
- }
2771
- FolderSyncUtil.parseStore = parseStore;
2772
- function is(text) {
2773
- return String(text ?? "").trim().startsWith("ta-sync://folder#");
2774
- }
2775
- FolderSyncUtil.is = is;
2776
- function parse(text) {
2777
- const value = String(text ?? "").trim();
2778
- const fragment = new URLSearchParams(value.slice(value.indexOf("#") + 1));
2779
- const [id, key, path] = ["s", "k", "p"].map((name) => fragment.get(name) ?? "");
2780
- if (!is(value) || fragment.get("v") !== "1" || !/^[A-Za-z0-9_-]{16,64}$/.test(id) || !/^[A-Za-z0-9_-]{43}$/.test(key) || !path) {
2781
- throw new Error("This is not a link of sync in a folder.");
2782
- }
2783
- return { id, key, path, name: fragment.get("n") ?? "" };
2784
- }
2785
- FolderSyncUtil.parse = parse;
2786
- })(FolderSyncUtil ||= {});
2787
-
2788
- class LocalFolderStore {
2789
- root;
2790
- constructor(root) {
2791
- this.root = root;
2792
- }
2793
- async list(dir) {
2794
- const found = [];
2795
- const at = join5(this.root, ...dir.split("/").filter(Boolean));
2796
- for (const entry of await readdir4(at, { withFileTypes: true }).catch(() => [])) {
2797
- if (entry.name.startsWith(".")) {
2798
- continue;
2799
- }
2800
- if (entry.isDirectory()) {
2801
- found.push({ name: entry.name, tag: "", dir: true });
2802
- } else if (entry.isFile()) {
2803
- const info = await stat4(join5(at, entry.name)).catch(() => {
2804
- return;
2805
- });
2806
- if (info) {
2807
- found.push({ name: entry.name, tag: `${info.mtimeMs}:${info.size}` });
2808
- }
3014
+ if (entry.isDirectory()) {
3015
+ found.push({ name: entry.name, tag: "", dir: true });
3016
+ } else if (entry.isFile()) {
3017
+ const info = await stat5(join6(at, entry.name)).catch(() => {
3018
+ return;
3019
+ });
3020
+ if (info) {
3021
+ found.push({ name: entry.name, tag: `${info.mtimeMs}:${info.size}` });
3022
+ }
2809
3023
  }
2810
3024
  }
2811
3025
  return found.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
2812
3026
  }
2813
3027
  async read(path) {
2814
3028
  try {
2815
- return new Uint8Array(await readFile3(this.path(path)));
3029
+ return new Uint8Array(await readFile4(this.path(path)));
2816
3030
  } catch {
2817
3031
  return;
2818
3032
  }
2819
3033
  }
2820
3034
  async write(path, data) {
2821
3035
  const file = this.path(path);
2822
- const dir = join5(file, "..");
3036
+ const dir = join6(file, "..");
2823
3037
  await mkdir4(dir, { recursive: true });
2824
- const temporary = join5(dir, `.${file.split(sep3).pop()}.${process.pid}.tmp`);
3038
+ const temporary = join6(dir, `.${file.split(sep3).pop()}.${process.pid}.tmp`);
2825
3039
  await writeFile3(temporary, data);
2826
3040
  await rename4(temporary, file);
2827
3041
  }
@@ -2839,7 +3053,7 @@ class LocalFolderStore {
2839
3053
  return () => watcher?.close();
2840
3054
  }
2841
3055
  path(path) {
2842
- return join5(this.root, ...path.split("/").filter(Boolean));
3056
+ return join6(this.root, ...path.split("/").filter(Boolean));
2843
3057
  }
2844
3058
  }
2845
3059
 
@@ -3045,32 +3259,216 @@ class FolderSpace extends StoreSpace {
3045
3259
  this.folder = folder;
3046
3260
  }
3047
3261
  get dir() {
3048
- return join5(this.folder, DIR, this.record.id);
3262
+ return join6(this.folder, DIR, this.record.id);
3049
3263
  }
3050
3264
  }
3051
3265
 
3052
- // web-src/sync-identity.ts
3053
- var SyncIdentityKeys;
3054
- ((SyncIdentityKeys) => {
3055
- SyncIdentityKeys.PREFIX = "id:";
3056
- SyncIdentityKeys.IDENTITY = "id:identity";
3057
- SyncIdentityKeys.ROOM = "id:room:";
3058
- SyncIdentityKeys.FRIENDS = "id:friends";
3059
- function room(member) {
3060
- return `${SyncIdentityKeys.ROOM}${member}`;
3061
- }
3062
- SyncIdentityKeys.room = room;
3063
- })(SyncIdentityKeys ||= {});
3064
- var MAX_FRIENDS = 150;
3266
+ // web-src/sync-service-space.ts
3267
+ import { mkdir as mkdir6, readFile as readFile6, rename as rename6, writeFile as writeFile5 } from "node:fs/promises";
3268
+ import { platform as platform3 } from "node:os";
3269
+ import { join as join8 } from "node:path";
3065
3270
 
3066
- class SyncIdentity {
3271
+ // web-src/sync-service-base.ts
3272
+ import { mkdir as mkdir5, readFile as readFile5, rename as rename5, writeFile as writeFile4 } from "node:fs/promises";
3273
+ import { hostname as hostname3, platform as platform2 } from "node:os";
3274
+ import { join as join7 } from "node:path";
3275
+
3276
+ // web-src/sync-engine.ts
3277
+ var ATTEMPTS = 3;
3278
+ var TOMBSTONE_MS = 90 * 24 * 60 * 60 * 1000;
3279
+
3280
+ class SyncEngine {
3067
3281
  room;
3068
- side;
3069
- skip;
3070
- constructor(room, side, skip) {
3282
+ place;
3283
+ device;
3284
+ now;
3285
+ constructor(room, place, device, now = Date.now) {
3071
3286
  this.room = room;
3072
- this.side = side;
3073
- this.skip = skip;
3287
+ this.place = place;
3288
+ this.device = device;
3289
+ this.now = now;
3290
+ }
3291
+ async round(base, resources) {
3292
+ const report = { at: this.now(), sent: 0, received: 0, skipped: [] };
3293
+ for (let attempt = 0;attempt < ATTEMPTS; attempt++) {
3294
+ const raced = await this.once(base, resources, report);
3295
+ if (!raced) {
3296
+ break;
3297
+ }
3298
+ }
3299
+ await this.dropOldMarks();
3300
+ return report;
3301
+ }
3302
+ async once(base, resources, report) {
3303
+ const remote = await this.remote();
3304
+ const local = await this.place.read(resources);
3305
+ const ids = new Set([...local.keys(), ...remote.keys(), ...Object.keys(base.items)]);
3306
+ let raced = false;
3307
+ for (const id of [...ids].sort()) {
3308
+ const resource = SyncItems.resourceOf(id);
3309
+ if (!resource || !resources.has(resource)) {
3310
+ continue;
3311
+ }
3312
+ try {
3313
+ raced = await this.item(id, local.get(id), remote.get(id), base, report) || raced;
3314
+ } catch (error) {
3315
+ report.skipped.push({ id, reason: error instanceof Error ? error.message : String(error) });
3316
+ }
3317
+ }
3318
+ return raced;
3319
+ }
3320
+ async item(id, local, remote, base, report) {
3321
+ const type = local?.type ?? remote?.entry.t ?? "bytes";
3322
+ const mergeable = type === "json" || type === "set";
3323
+ const had = base.items[id];
3324
+ const action = SyncMerge.decide(local, remote?.entry, had?.h, mergeable && (local?.type ?? type) === (remote?.entry.t ?? type));
3325
+ switch (action) {
3326
+ case "none":
3327
+ base.items[id] = { h: local?.h ?? "", ...local?.value === undefined ? {} : { v: local.value } };
3328
+ return false;
3329
+ case "forget":
3330
+ delete base.items[id];
3331
+ return false;
3332
+ case "push":
3333
+ case "keepLocal": {
3334
+ if (action === "keepLocal" && remote) {
3335
+ const theirs = await this.content(remote.entry);
3336
+ if (theirs) {
3337
+ await this.place.keep(id, remote.entry.t, theirs, remote.entry.by);
3338
+ }
3339
+ }
3340
+ const ok = await this.send(id, local, remote);
3341
+ if (ok) {
3342
+ base.items[id] = { h: local?.h ?? "", ...local?.value === undefined ? {} : { v: local.value } };
3343
+ report.sent++;
3344
+ }
3345
+ return !ok;
3346
+ }
3347
+ case "pull":
3348
+ case "keepRemote": {
3349
+ const entry = remote?.entry;
3350
+ const content = entry && !entry.deleted ? await this.content(entry) : undefined;
3351
+ if (entry && !entry.deleted && !content) {
3352
+ return false;
3353
+ }
3354
+ const aside = !!local && (action === "keepRemote" || had === undefined || local.h !== had.h);
3355
+ await this.place.apply(id, entry?.t ?? type, content, aside);
3356
+ base.items[id] = { h: content ? entry?.h ?? "" : "", ...content && mergeable ? { v: SyncCodec.parse(content) } : {} };
3357
+ if (local || content) {
3358
+ report.received++;
3359
+ }
3360
+ return false;
3361
+ }
3362
+ case "merge":
3363
+ return this.merge(id, local, remote, had, base, report);
3364
+ }
3365
+ }
3366
+ async merge(id, local, remote, had, base, report) {
3367
+ const content = await this.content(remote.entry);
3368
+ if (!content) {
3369
+ return false;
3370
+ }
3371
+ const theirs = SyncCodec.parse(content);
3372
+ const merged = local.type === "set" ? SyncMerge.set(Array.isArray(had?.v) ? had.v : undefined, Array.isArray(local.value) ? local.value : [], Array.isArray(theirs) ? theirs : []) : SyncMerge.value(had?.v, local.value, theirs);
3373
+ const item = SyncItems.item(id, local.type, SyncCodec.json(merged), this.now(), merged);
3374
+ if (item.h !== remote.entry.h && !await this.send(id, item, remote)) {
3375
+ return true;
3376
+ }
3377
+ if (item.h !== local.h) {
3378
+ await this.place.apply(id, local.type, item.bytes, false);
3379
+ report.received++;
3380
+ }
3381
+ if (item.h !== remote.entry.h) {
3382
+ report.sent++;
3383
+ }
3384
+ base.items[id] = { h: item.h, v: merged };
3385
+ return false;
3386
+ }
3387
+ async send(id, local, remote) {
3388
+ const entry = local ? { t: local.type, h: local.h, at: Math.round(local.at || this.now()), by: this.device, n: 0 } : { t: remote?.entry.t ?? "bytes", h: "", at: this.now(), by: this.device, n: 0, deleted: true };
3389
+ if (local) {
3390
+ const pieces = SyncCodec.encode(local.bytes, this.room.piece);
3391
+ entry.n = pieces.length;
3392
+ const there = await this.room.getState(`${SyncStateKeys.BLOB}${local.h}:`);
3393
+ for (const [index, piece] of pieces.entries()) {
3394
+ const key = SyncStateKeys.blob(local.h, index);
3395
+ if (there[key]?.value !== piece) {
3396
+ await this.room.setState(key, piece);
3397
+ }
3398
+ }
3399
+ }
3400
+ const result = await this.room.setState(SyncStateKeys.item(id), entry, remote?.version ?? 0);
3401
+ if (result.ok && remote && !remote.entry.deleted && remote.entry.h !== entry.h) {
3402
+ await this.dropBlob(remote.entry);
3403
+ }
3404
+ return result.ok;
3405
+ }
3406
+ async dropBlob(entry) {
3407
+ const remote = await this.remote();
3408
+ if ([...remote.values()].some(({ entry: other }) => !other.deleted && other.h === entry.h)) {
3409
+ return;
3410
+ }
3411
+ for (let index = 0;index < entry.n; index++) {
3412
+ await this.room.setState(SyncStateKeys.blob(entry.h, index), null);
3413
+ }
3414
+ }
3415
+ async content(entry) {
3416
+ const state = await this.room.getState(`${SyncStateKeys.BLOB}${entry.h}:`);
3417
+ const pieces = [];
3418
+ for (let index = 0;index < entry.n; index++) {
3419
+ const piece = state[SyncStateKeys.blob(entry.h, index)]?.value;
3420
+ if (typeof piece !== "string") {
3421
+ return;
3422
+ }
3423
+ pieces.push(piece);
3424
+ }
3425
+ const bytes = SyncCodec.decode(pieces);
3426
+ return SyncCodec.hash(bytes) === entry.h ? bytes : undefined;
3427
+ }
3428
+ async remote() {
3429
+ const items = new Map;
3430
+ for (const [key, { value, version }] of Object.entries(await this.room.getState(SyncStateKeys.ITEM))) {
3431
+ if (isEntry(value)) {
3432
+ items.set(key.slice(SyncStateKeys.ITEM.length), { entry: value, version });
3433
+ }
3434
+ }
3435
+ return items;
3436
+ }
3437
+ async dropOldMarks() {
3438
+ for (const [id, { entry, version }] of await this.remote()) {
3439
+ if (entry.deleted && this.now() - entry.at > TOMBSTONE_MS) {
3440
+ await this.room.setState(SyncStateKeys.item(id), null, version);
3441
+ }
3442
+ }
3443
+ }
3444
+ }
3445
+ function isEntry(value) {
3446
+ const entry = value;
3447
+ return SyncMerge.isObject(value) && ["json", "set", "bytes", "tree"].includes(entry.t) && typeof entry.h === "string" && typeof entry.at === "number" && typeof entry.n === "number" && typeof entry.by === "string";
3448
+ }
3449
+
3450
+ // web-src/sync-identity.ts
3451
+ var SyncIdentityKeys;
3452
+ ((SyncIdentityKeys) => {
3453
+ SyncIdentityKeys.PREFIX = "id:";
3454
+ SyncIdentityKeys.IDENTITY = "id:identity";
3455
+ SyncIdentityKeys.ROOM = "id:room:";
3456
+ SyncIdentityKeys.FRIENDS = "id:friends";
3457
+ function room(member) {
3458
+ return `${SyncIdentityKeys.ROOM}${member}`;
3459
+ }
3460
+ SyncIdentityKeys.room = room;
3461
+ })(SyncIdentityKeys ||= {});
3462
+ var MAX_FRIENDS = 150;
3463
+
3464
+ class SyncIdentity {
3465
+ room;
3466
+ side;
3467
+ skip;
3468
+ constructor(room, side, skip) {
3469
+ this.room = room;
3470
+ this.side = side;
3471
+ this.skip = skip;
3074
3472
  }
3075
3473
  async round(base) {
3076
3474
  const report = { switched: false, sent: 0, received: 0 };
@@ -3224,8 +3622,8 @@ var SyncIdentityUtil;
3224
3622
  SyncIdentityUtil.byId = byId;
3225
3623
  })(SyncIdentityUtil ||= {});
3226
3624
 
3227
- // web-src/sync-service.ts
3228
- class SyncService {
3625
+ // web-src/sync-service-base.ts
3626
+ class SyncServiceBase {
3229
3627
  options;
3230
3628
  device;
3231
3629
  baseFile;
@@ -3245,288 +3643,63 @@ class SyncService {
3245
3643
  folderFile;
3246
3644
  constructor(options) {
3247
3645
  this.options = options;
3248
- this.device = options.device ?? SyncService.deviceName();
3249
- this.baseFile = join6(options.agentDir, "sync", "base.json");
3250
- this.folderFile = join6(options.agentDir, "sync", "folder.json");
3646
+ this.device = options.device ?? SyncServiceBase.deviceName();
3647
+ this.baseFile = join7(options.agentDir, "sync", "base.json");
3648
+ this.folderFile = join7(options.agentDir, "sync", "folder.json");
3251
3649
  }
3252
3650
  static deviceName() {
3253
3651
  return hostname3().replace(/\.local$/, "") || platform2();
3254
3652
  }
3255
- start() {
3256
- this.stops.push(this.options.rooms.onEvent((event) => this.heard(event)));
3257
- this.look = setInterval(() => void this.lookAround(), this.options.lookMs ?? 30000);
3258
- this.options.storage.get(SyncKeys.REPORT).then((report) => {
3259
- this.report ??= report;
3260
- });
3261
- this.schedule(2000);
3653
+ heard(event) {
3654
+ if (event.type === "rooms" || event.type === "request") {
3655
+ this.publish();
3656
+ return;
3657
+ }
3658
+ if (event.type === "state" && (event.key.startsWith(SyncStateKeys.ITEM) || event.key.startsWith(SyncStateKeys.BLOB) || event.key.startsWith(SyncIdentityKeys.PREFIX))) {
3659
+ this.room().then((room) => {
3660
+ const self = room?.members.find((member) => member.self)?.member;
3661
+ if (room?.id === event.room && event.by !== self) {
3662
+ this.schedule();
3663
+ }
3664
+ });
3665
+ }
3262
3666
  }
3263
- dispose() {
3264
- this.stopped = true;
3265
- clearTimeout(this.timer);
3266
- clearInterval(this.look);
3267
- this.space?.stop();
3268
- for (const stop of this.stops) {
3269
- stop();
3667
+ schedule(delay = this.options.delayMs ?? 1500) {
3668
+ if (this.stopped) {
3669
+ return;
3270
3670
  }
3671
+ clearTimeout(this.timer);
3672
+ this.timer = setTimeout(() => void this.run(), delay);
3271
3673
  }
3272
- dataChanged(name, key) {
3273
- if (name === SYNC_PACKAGE ? key === SyncKeys.RESOURCES : this.options.place.tracks(name, key)) {
3274
- this.schedule();
3674
+ run() {
3675
+ if (this.running) {
3676
+ this.again = true;
3677
+ return this.running;
3275
3678
  }
3679
+ this.running = this.round().catch((error) => {
3680
+ this.report = { at: Date.now(), sent: 0, received: 0, skipped: [], error: error instanceof Error ? error.message : String(error) };
3681
+ }).finally(async () => {
3682
+ this.running = undefined;
3683
+ await this.options.storage.set(SyncKeys.REPORT, this.report).catch(() => {
3684
+ return;
3685
+ });
3686
+ await this.publish();
3687
+ if (this.again && !this.stopped) {
3688
+ this.again = false;
3689
+ this.schedule(0);
3690
+ }
3691
+ });
3692
+ this.publish();
3693
+ return this.running;
3276
3694
  }
3277
- async status() {
3278
- const resources = await this.resources();
3279
- const replaced = { dir: this.options.place.replacedDir, count: await this.options.place.replacedCount() };
3280
- const common = { resources, syncing: !!this.running, last: this.report, replaced };
3695
+ async round() {
3281
3696
  const folder = await this.folderRecord();
3282
- if (folder?.service) {
3283
- const opened = await this.openSpace(folder);
3284
- const problem = opened.problem ?? await this.problemOf(opened.space, folder);
3285
- const service = (await this.options.relays?.list().catch(() => {
3286
- return;
3287
- }) ?? []).find((each) => each.id === folder.service);
3288
- return {
3289
- state: "on",
3290
- where: "store",
3291
- via: service?.name ?? service?.where ?? folder.type ?? "",
3292
- store: { type: folder.type ?? service?.type ?? "", where: service?.where ?? "", ...problem ? { problem } : {} },
3293
- owner: false,
3294
- connected: !problem,
3295
- devices: problem || !opened.space ? [] : await this.folderDevices(opened.space),
3296
- asks: [],
3297
- ...common
3298
- };
3299
- }
3300
- if (folder) {
3301
- const opened = await this.openSpace(folder);
3302
- const space = opened.space;
3303
- const problem = opened.problem ?? await this.problemOf(space, folder);
3304
- const target = await this.target();
3305
- const named = target.type === "folder" && target.path && RelayServiceUtil.expand(target.path) === RelayServiceUtil.expand(folder.path) ? target.name : undefined;
3306
- return {
3307
- state: "on",
3308
- where: "folder",
3309
- via: named ?? SyncService.lastPart(folder.path),
3310
- folder: { path: RelayServiceUtil.expand(folder.path), ...problem ? { problem } : {} },
3311
- owner: false,
3312
- connected: !problem,
3313
- devices: problem ? [] : await this.folderDevices(space),
3314
- asks: [],
3315
- ...common
3316
- };
3317
- }
3318
- const room = await this.room();
3319
- if (!room) {
3320
- const target = await this.target();
3321
- return {
3322
- state: "off",
3323
- where: target.type === "ta-relay" ? "relay" : target.type,
3324
- via: target.name ?? (target.type === "folder" ? SyncService.lastPart(target.path ?? "") : target.type === "store" ? target.where : target.host),
3325
- ...target.type === "folder" ? { folder: { path: RelayServiceUtil.expand(target.path ?? "") } } : {},
3326
- ...target.type === "store" ? { store: { type: target.store ?? "", where: target.where ?? "" } } : {},
3327
- owner: false,
3328
- connected: false,
3329
- devices: [],
3330
- asks: [],
3331
- ...common
3332
- };
3333
- }
3334
- const state = room.status === "member" ? "on" : room.status;
3335
- return {
3336
- state,
3337
- where: "relay",
3338
- ...room.relay ? { via: await this.relayName(room.relay) } : {},
3339
- owner: room.owner,
3340
- ownerName: room.ownerName,
3341
- connected: room.connected,
3342
- devices: state === "on" ? await this.devices(room) : [],
3343
- asks: room.owner ? (await this.options.rooms.listRequests().catch(() => [])).filter((request) => request.room === room.id && !request.guest).map(({ ask, name, at }) => ({ ask, name, at })) : [],
3344
- ...common
3345
- };
3346
- }
3347
- async enable() {
3348
- const target = await this.target();
3349
- if (target.type === "folder" && target.path || target.type === "store" && target.id) {
3350
- const before = await this.room();
3351
- if (before) {
3352
- await this.options.rooms.leave(before.id);
3353
- }
3354
- const current = await this.folderRecord();
3355
- const same = !!current && (target.type === "store" ? current.service === target.id : !current.service && RelayServiceUtil.expand(current.path) === RelayServiceUtil.expand(target.path ?? ""));
3356
- if (!same) {
3357
- const record = {
3358
- id: FolderSyncUtil.randomId(),
3359
- key: FolderSyncUtil.randomKey(),
3360
- path: target.type === "folder" ? target.path ?? "" : "",
3361
- ...target.type === "store" ? { service: target.id, type: target.store } : {},
3362
- device: FolderSyncUtil.randomId(),
3363
- at: Date.now()
3364
- };
3365
- const problem = target.type === "folder" ? RelayServiceUtil.checkFolder(record.path) : undefined;
3366
- if (problem) {
3367
- throw new Error(problem);
3368
- }
3369
- const opened = await this.openSpace(record);
3370
- if (!opened.space) {
3371
- throw new Error(opened.problem);
3372
- }
3373
- await opened.space.create();
3374
- await this.saveFolder(record);
3375
- }
3376
- await this.publish();
3377
- this.schedule(0);
3378
- return this.status();
3379
- }
3380
- const room = await this.room();
3381
- if (room?.status !== "member") {
3382
- if (room) {
3383
- await this.options.rooms.leave(room.id);
3384
- }
3385
- await this.options.rooms.createRoom({ kind: SYNC_KIND, title: SyncServerTexts.title(), view: SYNC_VIEW, unlisted: true, use: "sync" });
3386
- }
3387
- this.schedule(0);
3388
- return this.status();
3389
- }
3390
- async invite(renew = false) {
3391
- const folder = await this.folderRecord();
3392
- if (folder?.service) {
3393
- const config = await this.options.relays?.storeConfig(folder.service);
3394
- if (!config) {
3395
- throw new Error(SyncServerTexts.storeUnavailable(folder.type ?? ""));
3396
- }
3397
- return { link: FolderSyncUtil.storeLink(folder, config, this.device), expiresAt: 0 };
3398
- }
3399
- if (folder) {
3400
- return { link: FolderSyncUtil.link(folder, this.device), expiresAt: 0 };
3401
- }
3402
- const room = await this.room();
3403
- if (room?.status !== "member") {
3404
- throw new Error(SyncServerTexts.notOn());
3405
- }
3406
- if (!room.owner) {
3407
- throw new Error(SyncServerTexts.notOwner(room.ownerName));
3408
- }
3409
- return this.options.rooms.invite(room.id, { renew });
3410
- }
3411
- async join(link) {
3412
- const room = await this.room();
3413
- if (room?.status === "member" || await this.folderRecord()) {
3414
- throw new Error(SyncServerTexts.alreadyOn());
3415
- }
3416
- if (FolderSyncUtil.is(link)) {
3417
- return this.joinFolder(link);
3418
- }
3419
- if (FolderSyncUtil.isStore(link)) {
3420
- return this.joinStore(link);
3421
- }
3422
- if (room) {
3423
- await this.options.rooms.leave(room.id);
3424
- }
3425
- const joined = await this.options.rooms.join(link);
3426
- await this.options.storage.set(SyncKeys.JOINING, joined.id);
3427
- await this.publish();
3428
- return this.status();
3429
- }
3430
- async leave() {
3431
- const folder = await this.folderRecord();
3432
- if (folder) {
3433
- this.space?.stop();
3434
- this.space = undefined;
3435
- await rm4(this.folderFile, { force: true });
3436
- }
3437
- const room = await this.room();
3438
- if (room) {
3439
- await this.options.rooms.leave(room.id);
3440
- }
3441
- await this.options.storage.set(SyncKeys.JOINING, null);
3442
- await this.saveBase({ room: "", items: {} });
3443
- await this.publish();
3444
- return this.status();
3445
- }
3446
- async answer(ask, accept) {
3447
- const room = await this.room();
3448
- if (room?.owner) {
3449
- await this.options.rooms.answer(room.id, ask, accept);
3450
- }
3451
- await this.publish();
3452
- return this.status();
3453
- }
3454
- async removeDevice(member) {
3455
- const room = await this.room();
3456
- if (room?.owner) {
3457
- await this.options.rooms.removeMember(room.id, member);
3458
- await this.options.rooms.setState(room.id, SyncStateKeys.device(member), null).catch(() => {
3459
- return;
3460
- });
3461
- }
3462
- return this.status();
3463
- }
3464
- async setResources(change) {
3465
- const resources = { ...await this.resources() };
3466
- for (const resource of SYNC_RESOURCES) {
3467
- if (typeof change?.[resource] === "boolean") {
3468
- resources[resource] = change[resource];
3469
- }
3470
- }
3471
- await this.options.storage.set(SyncKeys.RESOURCES, resources);
3472
- this.schedule(0);
3473
- return this.status();
3474
- }
3475
- async syncNow() {
3476
- clearTimeout(this.timer);
3477
- await this.run();
3478
- return this.status();
3479
- }
3480
- heard(event) {
3481
- if (event.type === "rooms" || event.type === "request") {
3482
- this.publish();
3483
- return;
3484
- }
3485
- if (event.type === "state" && (event.key.startsWith(SyncStateKeys.ITEM) || event.key.startsWith(SyncStateKeys.BLOB) || event.key.startsWith(SyncIdentityKeys.PREFIX))) {
3486
- this.room().then((room) => {
3487
- const self = room?.members.find((member) => member.self)?.member;
3488
- if (room?.id === event.room && event.by !== self) {
3489
- this.schedule();
3490
- }
3491
- });
3492
- }
3493
- }
3494
- schedule(delay = this.options.delayMs ?? 1500) {
3495
- if (this.stopped) {
3496
- return;
3497
- }
3498
- clearTimeout(this.timer);
3499
- this.timer = setTimeout(() => void this.run(), delay);
3500
- }
3501
- run() {
3502
- if (this.running) {
3503
- this.again = true;
3504
- return this.running;
3505
- }
3506
- this.running = this.round().catch((error) => {
3507
- this.report = { at: Date.now(), sent: 0, received: 0, skipped: [], error: error instanceof Error ? error.message : String(error) };
3508
- }).finally(async () => {
3509
- this.running = undefined;
3510
- await this.options.storage.set(SyncKeys.REPORT, this.report).catch(() => {
3511
- return;
3512
- });
3513
- await this.publish();
3514
- if (this.again && !this.stopped) {
3515
- this.again = false;
3516
- this.schedule(0);
3517
- }
3518
- });
3519
- this.publish();
3520
- return this.running;
3521
- }
3522
- async round() {
3523
- const folder = await this.folderRecord();
3524
- const room = folder ? undefined : await this.room();
3525
- if (!folder && room?.status !== "member") {
3526
- return;
3527
- }
3528
- let target;
3529
- if (folder) {
3697
+ const room = folder ? undefined : await this.room();
3698
+ if (!folder && room?.status !== "member") {
3699
+ return;
3700
+ }
3701
+ let target;
3702
+ if (folder) {
3530
3703
  const opened = await this.openSpace(folder);
3531
3704
  const problem = opened.problem ?? await this.problemOf(opened.space, folder);
3532
3705
  if (problem || !opened.space) {
@@ -3581,21 +3754,101 @@ class SyncService {
3581
3754
  this.schedule(0);
3582
3755
  }
3583
3756
  }
3584
- async target() {
3585
- const service = await this.options.relays?.serviceFor("sync").catch(() => {
3757
+ roomOf(id) {
3758
+ const rooms = this.options.rooms;
3759
+ return {
3760
+ getState: (prefix) => rooms.getState(id, prefix),
3761
+ setState: (key, value, version) => rooms.setState(id, key, value, version)
3762
+ };
3763
+ }
3764
+ async room() {
3765
+ const joining = await this.options.storage.get(SyncKeys.JOINING).catch(() => {
3586
3766
  return;
3587
3767
  });
3588
- const name = service?.builtin ? undefined : service?.name;
3589
- if (service?.type === "folder") {
3590
- return { type: "folder", path: service.path, id: service.id, ...name ? { name } : {} };
3591
- }
3592
- if (service && service.type !== "ta-relay") {
3768
+ const rooms = (await this.options.rooms.listRooms().catch(() => [])).filter((room) => room.kind === SYNC_KIND || room.id === joining && room.kind === "");
3769
+ const latest = (room) => room.joinedAt ?? room.createdAt;
3770
+ rooms.sort((a, b) => Number(b.status === "member") - Number(a.status === "member") || latest(b) - latest(a));
3771
+ return rooms[0];
3772
+ }
3773
+ async devices(room) {
3774
+ const state = await this.options.rooms.getState(room.id, SyncStateKeys.DEVICE).catch(() => ({}));
3775
+ return room.members.filter((member) => !member.guest).map((member) => {
3776
+ const entry = state[SyncStateKeys.device(member.member)]?.value;
3777
+ return {
3778
+ member: member.member,
3779
+ name: member.self ? this.device : entry?.name ?? member.name,
3780
+ platform: member.self ? platform2() : entry?.platform,
3781
+ online: member.online || member.self,
3782
+ self: member.self,
3783
+ owner: member.owner,
3784
+ ...entry?.at ? { at: entry.at } : {}
3785
+ };
3786
+ }).sort((a, b) => Number(b.self) - Number(a.self) || Number(b.owner) - Number(a.owner) || a.name.localeCompare(b.name));
3787
+ }
3788
+ resourcesNow = { ...DEFAULT_RESOURCES };
3789
+ async resources() {
3790
+ const saved = await this.options.storage.get(SyncKeys.RESOURCES).catch(() => {
3791
+ return;
3792
+ });
3793
+ const resources = { ...DEFAULT_RESOURCES };
3794
+ if (SyncMerge.isObject(saved)) {
3795
+ for (const resource of SYNC_RESOURCES) {
3796
+ if (typeof saved[resource] === "boolean") {
3797
+ resources[resource] = saved[resource];
3798
+ }
3799
+ }
3800
+ }
3801
+ this.resourcesNow = resources;
3802
+ return resources;
3803
+ }
3804
+ async publish() {
3805
+ const status = await this.status().catch(() => {
3806
+ return;
3807
+ });
3808
+ const text = status ? SyncMerge.canonical(status) : "";
3809
+ if (status && text !== this.shown) {
3810
+ if (status.state === "on" && this.state !== "on") {
3811
+ this.schedule(0);
3812
+ }
3813
+ this.state = status.state;
3814
+ this.shown = text;
3815
+ await this.options.storage.set(SyncKeys.STATUS, status).catch(() => {
3816
+ return;
3817
+ });
3818
+ }
3819
+ }
3820
+ async loadBase() {
3821
+ try {
3822
+ const data = JSON.parse(await readFile5(this.baseFile, "utf8"));
3823
+ return SyncMerge.isObject(data) && typeof data.room === "string" && SyncMerge.isObject(data.items) ? data : { room: "", items: {} };
3824
+ } catch {
3825
+ return { room: "", items: {} };
3826
+ }
3827
+ }
3828
+ async saveBase(base) {
3829
+ await mkdir5(join7(this.options.agentDir, "sync"), { recursive: true });
3830
+ await writeFile4(`${this.baseFile}.tmp`, JSON.stringify(base));
3831
+ await rename5(`${this.baseFile}.tmp`, this.baseFile);
3832
+ }
3833
+ }
3834
+
3835
+ // web-src/sync-service-space.ts
3836
+ class SyncServiceSpace extends SyncServiceBase {
3837
+ async target() {
3838
+ const service = await this.options.relays?.serviceFor("sync").catch(() => {
3839
+ return;
3840
+ });
3841
+ const name = service?.builtin ? undefined : service?.name;
3842
+ if (service?.type === "folder") {
3843
+ return { type: "folder", path: service.path, id: service.id, ...name ? { name } : {} };
3844
+ }
3845
+ if (service && service.type !== "ta-relay") {
3593
3846
  return { type: "store", id: service.id, store: service.type, where: service.where ?? service.type, ...name ? { name } : {} };
3594
3847
  }
3595
3848
  return {
3596
3849
  type: "ta-relay",
3597
3850
  name: service?.builtin || !service ? SyncServerTexts.official() : name,
3598
- host: SyncService.host(service?.url ?? "https://relay.cellbang.com")
3851
+ host: SyncServiceSpace.host(service?.url ?? "https://relay.cellbang.com")
3599
3852
  };
3600
3853
  }
3601
3854
  async relayName(url) {
@@ -3603,7 +3856,7 @@ class SyncService {
3603
3856
  return;
3604
3857
  }) ?? [];
3605
3858
  const named = relays.find((relay) => relay.url === url);
3606
- return named?.builtin ? SyncServerTexts.official() : named?.name ?? SyncService.host(url);
3859
+ return named?.builtin ? SyncServerTexts.official() : named?.name ?? SyncServiceSpace.host(url);
3607
3860
  }
3608
3861
  static host(url) {
3609
3862
  try {
@@ -3665,16 +3918,16 @@ class SyncService {
3665
3918
  }
3666
3919
  async folderRecord() {
3667
3920
  try {
3668
- const record = JSON.parse(await readFile4(this.folderFile, "utf8"));
3921
+ const record = JSON.parse(await readFile6(this.folderFile, "utf8"));
3669
3922
  return record && typeof record.id === "string" && typeof record.key === "string" && typeof record.path === "string" && typeof record.device === "string" ? record : undefined;
3670
3923
  } catch {
3671
3924
  return;
3672
3925
  }
3673
3926
  }
3674
3927
  async saveFolder(record) {
3675
- await mkdir5(join6(this.options.agentDir, "sync"), { recursive: true });
3676
- await writeFile4(`${this.folderFile}.tmp`, JSON.stringify(record), { mode: 384 });
3677
- await rename5(`${this.folderFile}.tmp`, this.folderFile);
3928
+ await mkdir6(join8(this.options.agentDir, "sync"), { recursive: true });
3929
+ await writeFile5(`${this.folderFile}.tmp`, JSON.stringify(record), { mode: 384 });
3930
+ await rename6(`${this.folderFile}.tmp`, this.folderFile);
3678
3931
  }
3679
3932
  async openSpace(record) {
3680
3933
  const where = record.service ? `store:${record.service}` : `folder:${record.path}`;
@@ -3738,85 +3991,238 @@ class SyncService {
3738
3991
  at: device.at
3739
3992
  }));
3740
3993
  if (self && !shown.some((device) => device.self)) {
3741
- shown.push({ member: self, name: this.device, platform: platform2(), online: true, self: true, owner: false });
3994
+ shown.push({ member: self, name: this.device, platform: platform3(), online: true, self: true, owner: false });
3742
3995
  }
3743
3996
  return shown.sort((a, b) => Number(b.self) - Number(a.self) || (b.at ?? 0) - (a.at ?? 0));
3744
3997
  }
3745
- roomOf(id) {
3746
- const rooms = this.options.rooms;
3747
- return {
3748
- getState: (prefix) => rooms.getState(id, prefix),
3749
- setState: (key, value, version) => rooms.setState(id, key, value, version)
3750
- };
3751
- }
3752
- async room() {
3753
- const joining = await this.options.storage.get(SyncKeys.JOINING).catch(() => {
3754
- return;
3998
+ }
3999
+
4000
+ // web-src/sync-service.ts
4001
+ class SyncService extends SyncServiceSpace {
4002
+ start() {
4003
+ this.stops.push(this.options.rooms.onEvent((event) => this.heard(event)));
4004
+ this.look = setInterval(() => void this.lookAround(), this.options.lookMs ?? 30000);
4005
+ this.options.storage.get(SyncKeys.REPORT).then((report) => {
4006
+ this.report ??= report;
3755
4007
  });
3756
- const rooms = (await this.options.rooms.listRooms().catch(() => [])).filter((room) => room.kind === SYNC_KIND || room.id === joining && room.kind === "");
3757
- const latest = (room) => room.joinedAt ?? room.createdAt;
3758
- rooms.sort((a, b) => Number(b.status === "member") - Number(a.status === "member") || latest(b) - latest(a));
3759
- return rooms[0];
4008
+ this.schedule(2000);
3760
4009
  }
3761
- async devices(room) {
3762
- const state = await this.options.rooms.getState(room.id, SyncStateKeys.DEVICE).catch(() => ({}));
3763
- return room.members.filter((member) => !member.guest).map((member) => {
3764
- const entry = state[SyncStateKeys.device(member.member)]?.value;
4010
+ dispose() {
4011
+ this.stopped = true;
4012
+ clearTimeout(this.timer);
4013
+ clearInterval(this.look);
4014
+ this.space?.stop();
4015
+ for (const stop of this.stops) {
4016
+ stop();
4017
+ }
4018
+ }
4019
+ dataChanged(name, key) {
4020
+ if (name === SYNC_PACKAGE ? key === SyncKeys.RESOURCES : this.options.place.tracks(name, key)) {
4021
+ this.schedule();
4022
+ }
4023
+ }
4024
+ async status() {
4025
+ const resources = await this.resources();
4026
+ const replaced = { dir: this.options.place.replacedDir, count: await this.options.place.replacedCount() };
4027
+ const common = { resources, syncing: !!this.running, last: this.report, replaced };
4028
+ const folder = await this.folderRecord();
4029
+ if (folder?.service) {
4030
+ const opened = await this.openSpace(folder);
4031
+ const problem = opened.problem ?? await this.problemOf(opened.space, folder);
4032
+ const service = (await this.options.relays?.list().catch(() => {
4033
+ return;
4034
+ }) ?? []).find((each) => each.id === folder.service);
3765
4035
  return {
3766
- member: member.member,
3767
- name: member.self ? this.device : entry?.name ?? member.name,
3768
- platform: member.self ? platform2() : entry?.platform,
3769
- online: member.online || member.self,
3770
- self: member.self,
3771
- owner: member.owner,
3772
- ...entry?.at ? { at: entry.at } : {}
4036
+ state: "on",
4037
+ where: "store",
4038
+ via: service?.name ?? service?.where ?? folder.type ?? "",
4039
+ store: { type: folder.type ?? service?.type ?? "", where: service?.where ?? "", ...problem ? { problem } : {} },
4040
+ owner: false,
4041
+ connected: !problem,
4042
+ devices: problem || !opened.space ? [] : await this.folderDevices(opened.space),
4043
+ asks: [],
4044
+ ...common
3773
4045
  };
3774
- }).sort((a, b) => Number(b.self) - Number(a.self) || Number(b.owner) - Number(a.owner) || a.name.localeCompare(b.name));
4046
+ }
4047
+ if (folder) {
4048
+ const opened = await this.openSpace(folder);
4049
+ const space = opened.space;
4050
+ const problem = opened.problem ?? await this.problemOf(space, folder);
4051
+ const target = await this.target();
4052
+ const named = target.type === "folder" && target.path && RelayServiceUtil.expand(target.path) === RelayServiceUtil.expand(folder.path) ? target.name : undefined;
4053
+ return {
4054
+ state: "on",
4055
+ where: "folder",
4056
+ via: named ?? SyncService.lastPart(folder.path),
4057
+ folder: { path: RelayServiceUtil.expand(folder.path), ...problem ? { problem } : {} },
4058
+ owner: false,
4059
+ connected: !problem,
4060
+ devices: problem ? [] : await this.folderDevices(space),
4061
+ asks: [],
4062
+ ...common
4063
+ };
4064
+ }
4065
+ const room = await this.room();
4066
+ if (!room) {
4067
+ const target = await this.target();
4068
+ return {
4069
+ state: "off",
4070
+ where: target.type === "ta-relay" ? "relay" : target.type,
4071
+ via: target.name ?? (target.type === "folder" ? SyncService.lastPart(target.path ?? "") : target.type === "store" ? target.where : target.host),
4072
+ ...target.type === "folder" ? { folder: { path: RelayServiceUtil.expand(target.path ?? "") } } : {},
4073
+ ...target.type === "store" ? { store: { type: target.store ?? "", where: target.where ?? "" } } : {},
4074
+ owner: false,
4075
+ connected: false,
4076
+ devices: [],
4077
+ asks: [],
4078
+ ...common
4079
+ };
4080
+ }
4081
+ const state = room.status === "member" ? "on" : room.status;
4082
+ return {
4083
+ state,
4084
+ where: "relay",
4085
+ ...room.relay ? { via: await this.relayName(room.relay) } : {},
4086
+ owner: room.owner,
4087
+ ownerName: room.ownerName,
4088
+ connected: room.connected,
4089
+ devices: state === "on" ? await this.devices(room) : [],
4090
+ asks: room.owner ? (await this.options.rooms.listRequests().catch(() => [])).filter((request) => request.room === room.id && !request.guest).map(({ ask, name, at }) => ({ ask, name, at })) : [],
4091
+ ...common
4092
+ };
3775
4093
  }
3776
- resourcesNow = { ...DEFAULT_RESOURCES };
3777
- async resources() {
3778
- const saved = await this.options.storage.get(SyncKeys.RESOURCES).catch(() => {
3779
- return;
3780
- });
3781
- const resources = { ...DEFAULT_RESOURCES };
3782
- if (SyncMerge.isObject(saved)) {
3783
- for (const resource of SYNC_RESOURCES) {
3784
- if (typeof saved[resource] === "boolean") {
3785
- resources[resource] = saved[resource];
4094
+ async enable() {
4095
+ const target = await this.target();
4096
+ if (target.type === "folder" && target.path || target.type === "store" && target.id) {
4097
+ const before = await this.room();
4098
+ if (before) {
4099
+ await this.options.rooms.leave(before.id);
4100
+ }
4101
+ const current = await this.folderRecord();
4102
+ const same = !!current && (target.type === "store" ? current.service === target.id : !current.service && RelayServiceUtil.expand(current.path) === RelayServiceUtil.expand(target.path ?? ""));
4103
+ if (!same) {
4104
+ const record = {
4105
+ id: FolderSyncUtil.randomId(),
4106
+ key: FolderSyncUtil.randomKey(),
4107
+ path: target.type === "folder" ? target.path ?? "" : "",
4108
+ ...target.type === "store" ? { service: target.id, type: target.store } : {},
4109
+ device: FolderSyncUtil.randomId(),
4110
+ at: Date.now()
4111
+ };
4112
+ const problem = target.type === "folder" ? RelayServiceUtil.checkFolder(record.path) : undefined;
4113
+ if (problem) {
4114
+ throw new Error(problem);
4115
+ }
4116
+ const opened = await this.openSpace(record);
4117
+ if (!opened.space) {
4118
+ throw new Error(opened.problem);
3786
4119
  }
4120
+ await opened.space.create();
4121
+ await this.saveFolder(record);
3787
4122
  }
4123
+ await this.publish();
4124
+ this.schedule(0);
4125
+ return this.status();
3788
4126
  }
3789
- this.resourcesNow = resources;
3790
- return resources;
4127
+ const room = await this.room();
4128
+ if (room?.status !== "member") {
4129
+ if (room) {
4130
+ await this.options.rooms.leave(room.id);
4131
+ }
4132
+ await this.options.rooms.createRoom({ kind: SYNC_KIND, title: SyncServerTexts.title(), view: SYNC_VIEW, unlisted: true, use: "sync" });
4133
+ }
4134
+ this.schedule(0);
4135
+ return this.status();
3791
4136
  }
3792
- async publish() {
3793
- const status = await this.status().catch(() => {
3794
- return;
3795
- });
3796
- const text = status ? SyncMerge.canonical(status) : "";
3797
- if (status && text !== this.shown) {
3798
- if (status.state === "on" && this.state !== "on") {
3799
- this.schedule(0);
4137
+ async invite(renew = false) {
4138
+ const folder = await this.folderRecord();
4139
+ if (folder?.service) {
4140
+ const config = await this.options.relays?.storeConfig(folder.service);
4141
+ if (!config) {
4142
+ throw new Error(SyncServerTexts.storeUnavailable(folder.type ?? ""));
3800
4143
  }
3801
- this.state = status.state;
3802
- this.shown = text;
3803
- await this.options.storage.set(SyncKeys.STATUS, status).catch(() => {
4144
+ return { link: FolderSyncUtil.storeLink(folder, config, this.device), expiresAt: 0 };
4145
+ }
4146
+ if (folder) {
4147
+ return { link: FolderSyncUtil.link(folder, this.device), expiresAt: 0 };
4148
+ }
4149
+ const room = await this.room();
4150
+ if (room?.status !== "member") {
4151
+ throw new Error(SyncServerTexts.notOn());
4152
+ }
4153
+ if (!room.owner) {
4154
+ throw new Error(SyncServerTexts.notOwner(room.ownerName));
4155
+ }
4156
+ return this.options.rooms.invite(room.id, { renew });
4157
+ }
4158
+ async join(link) {
4159
+ const room = await this.room();
4160
+ if (room?.status === "member" || await this.folderRecord()) {
4161
+ throw new Error(SyncServerTexts.alreadyOn());
4162
+ }
4163
+ if (FolderSyncUtil.is(link)) {
4164
+ return this.joinFolder(link);
4165
+ }
4166
+ if (FolderSyncUtil.isStore(link)) {
4167
+ return this.joinStore(link);
4168
+ }
4169
+ if (room) {
4170
+ await this.options.rooms.leave(room.id);
4171
+ }
4172
+ const joined = await this.options.rooms.join(link);
4173
+ await this.options.storage.set(SyncKeys.JOINING, joined.id);
4174
+ await this.publish();
4175
+ return this.status();
4176
+ }
4177
+ async leave() {
4178
+ const folder = await this.folderRecord();
4179
+ if (folder) {
4180
+ this.space?.stop();
4181
+ this.space = undefined;
4182
+ await rm4(this.folderFile, { force: true });
4183
+ }
4184
+ const room = await this.room();
4185
+ if (room) {
4186
+ await this.options.rooms.leave(room.id);
4187
+ }
4188
+ await this.options.storage.set(SyncKeys.JOINING, null);
4189
+ await this.saveBase({ room: "", items: {} });
4190
+ await this.publish();
4191
+ return this.status();
4192
+ }
4193
+ async answer(ask, accept) {
4194
+ const room = await this.room();
4195
+ if (room?.owner) {
4196
+ await this.options.rooms.answer(room.id, ask, accept);
4197
+ }
4198
+ await this.publish();
4199
+ return this.status();
4200
+ }
4201
+ async removeDevice(member) {
4202
+ const room = await this.room();
4203
+ if (room?.owner) {
4204
+ await this.options.rooms.removeMember(room.id, member);
4205
+ await this.options.rooms.setState(room.id, SyncStateKeys.device(member), null).catch(() => {
3804
4206
  return;
3805
4207
  });
3806
4208
  }
4209
+ return this.status();
3807
4210
  }
3808
- async loadBase() {
3809
- try {
3810
- const data = JSON.parse(await readFile4(this.baseFile, "utf8"));
3811
- return SyncMerge.isObject(data) && typeof data.room === "string" && SyncMerge.isObject(data.items) ? data : { room: "", items: {} };
3812
- } catch {
3813
- return { room: "", items: {} };
4211
+ async setResources(change) {
4212
+ const resources = { ...await this.resources() };
4213
+ for (const resource of SYNC_RESOURCES) {
4214
+ if (typeof change?.[resource] === "boolean") {
4215
+ resources[resource] = change[resource];
4216
+ }
3814
4217
  }
4218
+ await this.options.storage.set(SyncKeys.RESOURCES, resources);
4219
+ this.schedule(0);
4220
+ return this.status();
3815
4221
  }
3816
- async saveBase(base) {
3817
- await mkdir5(join6(this.options.agentDir, "sync"), { recursive: true });
3818
- await writeFile4(`${this.baseFile}.tmp`, JSON.stringify(base));
3819
- await rename5(`${this.baseFile}.tmp`, this.baseFile);
4222
+ async syncNow() {
4223
+ clearTimeout(this.timer);
4224
+ await this.run();
4225
+ return this.status();
3820
4226
  }
3821
4227
  }
3822
4228
 
@@ -3840,7 +4246,7 @@ function hostSide(host) {
3840
4246
  if (!pkg.enabled) {
3841
4247
  continue;
3842
4248
  }
3843
- const manifest = await readFile5(join7(pkg.root, "package.json"), "utf8").then((text) => JSON.parse(text), () => {
4249
+ const manifest = await readFile7(join9(pkg.root, "package.json"), "utf8").then((text) => JSON.parse(text), () => {
3844
4250
  return;
3845
4251
  });
3846
4252
  keys.push(...SyncDeclarations.keys(manifest).map((key) => ({ name: pkg.name, key })));
@@ -3856,6 +4262,7 @@ function activate(host) {
3856
4262
  agentDir: host.agentDir,
3857
4263
  place: new AgentDirPlace(host.agentDir, side),
3858
4264
  side,
4265
+ ...typeof host.relocateDirectory === "function" ? { relocate: (from, to) => host.relocateDirectory(from, to) } : {},
3859
4266
  publish: (status) => void host.setExtensionData(SYNC_PACKAGE, MIGRATE_STATUS_KEY, status).catch(() => {
3860
4267
  return;
3861
4268
  })
@@ -3895,6 +4302,8 @@ function activate(host) {
3895
4302
  migrateExport: (categories, password, dir) => migrate.exportFile(categories, typeof password === "string" ? password : undefined, typeof dir === "string" && dir ? dir : undefined),
3896
4303
  migrateImport: (path, password) => migrate.importFile(String(path ?? ""), typeof password === "string" ? password : undefined),
3897
4304
  migrateBackups: () => migrate.listBackups(),
4305
+ migrateMissing: () => migrate.missing(),
4306
+ migrateRelocate: (from, to) => migrate.relocate(String(from ?? ""), String(to ?? "")),
3898
4307
  dispose: () => {
3899
4308
  stopData();
3900
4309
  service.dispose();