@rljson/fs-agent 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fs-agent.js CHANGED
@@ -8,7 +8,7 @@ import { dirname, join, relative, resolve, sep } from "path";
8
8
  import { Db, stateBeaconEvent } from "@rljson/db";
9
9
  import { IoMem, createSocketPair } from "@rljson/io";
10
10
  import { Client, Server } from "@rljson/server";
11
- //#region src/fs-signals.ts
11
+ // src/fs-signals.ts
12
12
  // @license
13
13
  /** How many signals {@link FsSignals.all} keeps. */
14
14
  var SIGNAL_LOG_MAX = 200;
@@ -196,8 +196,7 @@ var FsSignals = class FsSignals {
196
196
  return typeof entry.kind === "string" && typeof entry.at === "number" && Array.isArray(entry.paths) && typeof entry.pathCount === "number" && typeof entry.action === "string";
197
197
  }
198
198
  };
199
- //#endregion
200
- //#region src/fs-atomic-write.ts
199
+ // src/fs-atomic-write.ts
201
200
  // @license
202
201
  /**
203
202
  * Filename prefix for the staging files used by atomic writes.
@@ -327,8 +326,7 @@ var storeFileAsBlob = async (bs, handle, size) => {
327
326
  if (size <= 4194304) return bs.setBlob(await handle.readFile());
328
327
  return bs.setBlob(handle.readableWebStream());
329
328
  };
330
- //#endregion
331
- //#region src/fs-blob-adapter.ts
329
+ // src/fs-blob-adapter.ts
332
330
  // @license
333
331
  /**
334
332
  * Handles conversion between files and blobs in blob storage
@@ -442,8 +440,183 @@ var FsBlobAdapter = class FsBlobAdapter {
442
440
  return new FsBlobAdapter();
443
441
  }
444
442
  };
445
- //#endregion
446
- //#region src/fs-db-adapter.ts
443
+ // src/fs-carry.ts
444
+ // @license
445
+ /**
446
+ * A node's path, `.` for the root.
447
+ * @param node - The node.
448
+ * @returns Its relative path.
449
+ */
450
+ var pathOf = (node) => node.meta.relativePath;
451
+ /**
452
+ * Whether a node is a directory.
453
+ * @param node - The node.
454
+ * @returns True for a directory.
455
+ */
456
+ var isDirectory = (node) => node.meta.type === "directory";
457
+ /**
458
+ * The directory holding a path, `.` for a top-level one.
459
+ * @param path - A relative path other than `.`.
460
+ * @returns Its parent.
461
+ */
462
+ var parentOf = (path) => {
463
+ const slash = path.lastIndexOf("/");
464
+ return slash < 0 ? "." : path.slice(0, slash);
465
+ };
466
+ /**
467
+ * How deep a path is: `.` is 0, a top-level path 1.
468
+ * @param path - A relative path.
469
+ * @returns Its depth.
470
+ */
471
+ var depthOf = (path) => path === "." ? 0 : path.split("/").length;
472
+ /**
473
+ * The nodes of a tree a scan with this ignore rule leaves out.
474
+ *
475
+ * Walked from the root, as the scanner walks the folder: an ignored directory
476
+ * is taken whole, with everything below it, and nothing below it is asked.
477
+ * @param tree - The tree, typically a head's.
478
+ * @param ignores - The scanner's rule: a path, and whether it is a directory.
479
+ * @returns The left-out nodes, files and directories, by path.
480
+ */
481
+ var carriedNodes = (tree, ignores) => {
482
+ const carried = /* @__PURE__ */ new Map();
483
+ const childrenOf = (node) => node?.children ?? [];
484
+ const take = (node) => {
485
+ carried.set(pathOf(node), node);
486
+ for (const hash of childrenOf(node)) {
487
+ const child = tree.trees.get(hash);
488
+ if (child) take(child);
489
+ }
490
+ };
491
+ const visit = (node) => {
492
+ for (const hash of childrenOf(node)) {
493
+ const child = tree.trees.get(hash);
494
+ if (!child) continue;
495
+ if (ignores(pathOf(child), isDirectory(child))) take(child);
496
+ else if (isDirectory(child)) visit(child);
497
+ }
498
+ };
499
+ visit(tree.trees.get(tree.rootHash));
500
+ return carried;
501
+ };
502
+ /**
503
+ * A file node holding a version of another file under a new path — a merge
504
+ * keeping both versions of one file.
505
+ * @param path - Where the version is kept.
506
+ * @param blobId - The version.
507
+ * @param size - Its size in bytes.
508
+ * @returns The node, hashed, in the scanner's own format.
509
+ */
510
+ var fileNode = (path, blobId, size) => {
511
+ const name = path.slice(path.lastIndexOf("/") + 1);
512
+ const node = {
513
+ id: name,
514
+ isParent: false,
515
+ meta: {
516
+ name,
517
+ type: "file",
518
+ relativePath: path,
519
+ size,
520
+ blobId
521
+ },
522
+ children: null
523
+ };
524
+ hip(node);
525
+ return node;
526
+ };
527
+ /**
528
+ * A tree holding what `tree` holds and the carried nodes besides — built as
529
+ * the scanner builds one, so a folder that holds its carried paths after all
530
+ * gives the same ref either way.
531
+ *
532
+ * The folder's own entries come first: a carried path the scan holds itself
533
+ * is not carried, and neither is one below a path the scan holds as a file.
534
+ * A directory a carried path needs and the scan lacks — the folder lost it
535
+ * around a file it does not see — is put back, holding just that.
536
+ * @param tree - The folder, as scanned.
537
+ * @param carried - What to carry, by path — see {@link carriedNodes}. A file
538
+ * node is used as it is; every directory is rebuilt from its children.
539
+ * @returns The tree, and the carried paths it holds; `tree` itself when it
540
+ * holds none of them.
541
+ */
542
+ var graftTree = (tree, carried) => {
543
+ const added = /* @__PURE__ */ new Map();
544
+ if (carried.size === 0) return {
545
+ tree,
546
+ carried: added
547
+ };
548
+ const scanned = /* @__PURE__ */ new Map();
549
+ for (const node of tree.trees.values()) scanned.set(pathOf(node), node);
550
+ for (const path of [...carried.keys()].sort((a, b) => depthOf(a) - depthOf(b))) {
551
+ if (scanned.has(path)) continue;
552
+ let fits = true;
553
+ for (let at = parentOf(path); at !== "."; at = parentOf(at)) {
554
+ const holder = scanned.get(at) ?? added.get(at);
555
+ if (holder !== void 0 && !isDirectory(holder)) {
556
+ fits = false;
557
+ break;
558
+ }
559
+ }
560
+ if (fits) added.set(path, carried.get(path));
561
+ }
562
+ if (added.size === 0) return {
563
+ tree,
564
+ carried: added
565
+ };
566
+ const touched = /* @__PURE__ */ new Set();
567
+ for (const [path, node] of added) {
568
+ if (isDirectory(node)) touched.add(path);
569
+ for (let at = parentOf(path);; at = parentOf(at)) {
570
+ touched.add(at);
571
+ if (at === ".") break;
572
+ }
573
+ }
574
+ const members = /* @__PURE__ */ new Map();
575
+ const enter = (path) => {
576
+ if (path === ".") return;
577
+ const parent = parentOf(path);
578
+ if (!touched.has(parent)) return;
579
+ const list = members.get(parent);
580
+ if (list) list.push(path);
581
+ else members.set(parent, [path]);
582
+ };
583
+ for (const path of scanned.keys()) enter(path);
584
+ for (const path of added.keys()) if (!touched.has(path)) enter(path);
585
+ for (const path of touched) if (!scanned.has(path)) enter(path);
586
+ const trees = new Map(tree.trees);
587
+ for (const path of touched) {
588
+ const old = scanned.get(path);
589
+ if (old) trees.delete(old._hash);
590
+ }
591
+ for (const node of added.values()) if (!isDirectory(node)) trees.set(node._hash, node);
592
+ const rebuilt = /* @__PURE__ */ new Map();
593
+ for (const path of [...touched].sort((a, b) => depthOf(b) - depthOf(a))) {
594
+ const children = (members.get(path) ?? []).map((child) => (rebuilt.get(child) ?? scanned.get(child) ?? added.get(child))?._hash).sort();
595
+ const name = path === "." ? "." : path.slice(path.lastIndexOf("/") + 1);
596
+ const meta = {
597
+ name,
598
+ type: "directory",
599
+ relativePath: path
600
+ };
601
+ const node = {
602
+ id: name,
603
+ isParent: children.length > 0,
604
+ meta,
605
+ children: children.length > 0 ? children : null
606
+ };
607
+ hip(node);
608
+ rebuilt.set(path, node);
609
+ trees.set(node._hash, node);
610
+ }
611
+ return {
612
+ tree: {
613
+ rootHash: rebuilt.get(".")?._hash,
614
+ trees
615
+ },
616
+ carried: added
617
+ };
618
+ };
619
+ // src/fs-db-adapter.ts
447
620
  // @license
448
621
  /**
449
622
  * Adapter for storing filesystem trees in a database.
@@ -493,8 +666,7 @@ var FsDbAdapter = class {
493
666
  return this.db;
494
667
  }
495
668
  };
496
- //#endregion
497
- //#region src/fs-edit-chain.ts
669
+ // src/fs-edit-chain.ts
498
670
  // @license
499
671
  /** The `EditAction.type` every fs chain entry carries. */
500
672
  var FS_EDIT_ACTION = "putFsTree";
@@ -968,8 +1140,153 @@ var planJoin = (q) => {
968
1140
  conflict: conflict.sort()
969
1141
  };
970
1142
  };
971
- //#endregion
972
- //#region src/fs-merge.ts
1143
+ // src/fs-ignore.ts
1144
+ // @license
1145
+ /** Characters whose presence makes a pattern a glob rather than a prefix. */
1146
+ var GLOB_CHARS = /[*?/\\]/;
1147
+ /**
1148
+ * Escapes the regular-expression metacharacters that are NOT glob syntax.
1149
+ *
1150
+ * `*` and `?` are handled by the translator and must not reach this.
1151
+ * @param text - A run of literal characters from a glob.
1152
+ * @returns The same text, safe to embed in a regular expression.
1153
+ */
1154
+ var escapeLiteral = (text) => text.replace(/[.+^${}()|[\]\\\-]/g, "\\$&");
1155
+ /**
1156
+ * Translates a glob into an anchored, case-insensitive regular expression.
1157
+ *
1158
+ * `*` and `?` stop at a separator, `**` crosses them. A `**` followed by `/`
1159
+ * also matches ZERO directories, so `**\/x` matches `x` at the root as well as
1160
+ * at any depth — the one piece of gitignore's behaviour that is not obvious
1161
+ * from the characters.
1162
+ * @param glob - The pattern, separators already normalised to `/`.
1163
+ * @returns A regular expression matching the whole string.
1164
+ */
1165
+ var globToRegExp = (glob) => {
1166
+ let out = "";
1167
+ for (let i = 0; i < glob.length; i++) {
1168
+ const char = glob[i];
1169
+ if (char === "*") {
1170
+ if (glob[i + 1] === "*") {
1171
+ i++;
1172
+ if (glob[i + 1] === "/") {
1173
+ out += "(?:[^/]+/)*";
1174
+ i++;
1175
+ } else out += ".*";
1176
+ } else out += "[^/]*";
1177
+ } else if (char === "?") out += "[^/]";
1178
+ else out += escapeLiteral(char);
1179
+ }
1180
+ return new RegExp(`^${out}$`, "i");
1181
+ };
1182
+ /**
1183
+ * Normalises a path the way every comparison here expects it.
1184
+ *
1185
+ * Windows separators become `/`, a leading `./` or `/` goes, and a trailing
1186
+ * `/` goes — so one path has one spelling whichever side produced it. The
1187
+ * watcher reports `sub\dir\file` on Windows and `sub/dir/file` elsewhere for
1188
+ * the same file.
1189
+ * @param path - A path relative to the sync root.
1190
+ * @returns The normalised form.
1191
+ */
1192
+ var normalise = (path) => {
1193
+ const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
1194
+ return slashed === "." ? "" : slashed;
1195
+ };
1196
+ /**
1197
+ * Compiles one line of an ignore list.
1198
+ * @param pattern - The line, as the user or the product wrote it.
1199
+ * @returns The rule, or undefined for a blank line or a `#` comment.
1200
+ */
1201
+ var compileRule = (pattern) => {
1202
+ const trimmed = pattern.trim();
1203
+ if (trimmed === "" || trimmed.startsWith("#")) return void 0;
1204
+ const negated = trimmed.startsWith("!");
1205
+ const body = negated ? trimmed.slice(1) : trimmed;
1206
+ if (!negated && !GLOB_CHARS.test(body)) return {
1207
+ negated: false,
1208
+ dirOnly: false,
1209
+ kind: "literal",
1210
+ literal: body,
1211
+ re: void 0
1212
+ };
1213
+ const dirOnly = /[/\\]$/.test(body);
1214
+ const glob = normalise(body);
1215
+ if (glob === "") return void 0;
1216
+ return {
1217
+ negated,
1218
+ dirOnly,
1219
+ kind: glob.includes("/") ? "path" : "segment",
1220
+ literal: glob,
1221
+ re: globToRegExp(glob)
1222
+ };
1223
+ };
1224
+ /**
1225
+ * Whether one rule covers a path.
1226
+ * @param rule - The compiled rule.
1227
+ * @param path - The normalised relative path.
1228
+ * @param segments - That path, split on `/`.
1229
+ * @param isDirectory - True, false, or undefined when the caller cannot say.
1230
+ * @returns True when the rule matches.
1231
+ */
1232
+ var ruleMatches = (rule, path, segments, isDirectory) => {
1233
+ if (rule.kind === "literal") return segments.some((segment) => segment === rule.literal || segment.startsWith(rule.literal));
1234
+ const re = rule.re;
1235
+ if (rule.kind === "segment") {
1236
+ const last = segments.length - 1;
1237
+ return segments.some((segment, index) => {
1238
+ if (!re.test(segment)) return false;
1239
+ if (!rule.dirOnly) return true;
1240
+ return index < last || isDirectory !== false;
1241
+ });
1242
+ }
1243
+ if (re.test(path) && !(rule.dirOnly && isDirectory === false)) return true;
1244
+ let ancestor = "";
1245
+ for (const segment of segments.slice(0, -1)) {
1246
+ ancestor = ancestor === "" ? segment : `${ancestor}/${segment}`;
1247
+ if (re.test(ancestor)) return true;
1248
+ }
1249
+ return false;
1250
+ };
1251
+ /**
1252
+ * Compiles an ignore list into a matcher.
1253
+ *
1254
+ * **Order matters, and the LAST match decides** — the gitignore rule, and the
1255
+ * only one under which `!` can mean anything: `['*.log', '!keep.log']` keeps
1256
+ * `keep.log` and `['!keep.log', '*.log']` does not. One caveat inherited with
1257
+ * the semantics: the scanner does not descend into an ignored directory, so a
1258
+ * `!` line cannot rescue a file inside one.
1259
+ * @param patterns - The ignore list, in the order it was written.
1260
+ * @returns A matcher over those patterns.
1261
+ */
1262
+ var compileIgnore = (patterns) => {
1263
+ const rules = [];
1264
+ for (const pattern of patterns ?? []) {
1265
+ const rule = compileRule(pattern);
1266
+ if (rule !== void 0) rules.push(rule);
1267
+ }
1268
+ const ignores = (relativePath, isDirectory) => {
1269
+ const path = normalise(relativePath);
1270
+ if (path === "") return false;
1271
+ const segments = path.split("/").filter((s) => s !== "");
1272
+ let ignored = false;
1273
+ for (const rule of rules) if (ruleMatches(rule, path, segments, isDirectory)) ignored = !rule.negated;
1274
+ return ignored;
1275
+ };
1276
+ return {
1277
+ ignores,
1278
+ excludes: (relativePath, isDirectory) => {
1279
+ const segments = normalise(relativePath).split("/").filter((s) => s !== "");
1280
+ let above = "";
1281
+ for (const segment of segments.slice(0, -1)) {
1282
+ above = above === "" ? segment : `${above}/${segment}`;
1283
+ if (ignores(above, true)) return true;
1284
+ }
1285
+ return ignores(relativePath, isDirectory);
1286
+ }
1287
+ };
1288
+ };
1289
+ // src/fs-merge.ts
973
1290
  // @license
974
1291
  /** The value a directory has in a {@link ContentMap}. */
975
1292
  var DIR_MARKER = "<dir>";
@@ -1163,8 +1480,7 @@ var unusedName = (path, marker, taken) => {
1163
1480
  taken.add(candidate);
1164
1481
  return candidate;
1165
1482
  };
1166
- //#endregion
1167
- //#region src/fs-stamps.ts
1483
+ // src/fs-stamps.ts
1168
1484
  // @license
1169
1485
  /**
1170
1486
  * The table the stamps of one route's chain entries are kept in.
@@ -1409,8 +1725,7 @@ var FsStamps = class {
1409
1725
  return order < 0 || order === 0 && a < b;
1410
1726
  }
1411
1727
  };
1412
- //#endregion
1413
- //#region src/fs-history.ts
1728
+ // src/fs-history.ts
1414
1729
  // @license
1415
1730
  /** How many entries a page holds when the caller does not say. */
1416
1731
  var FS_HISTORY_PAGE = 50;
@@ -1543,8 +1858,7 @@ var readCursor = (cursor) => {
1543
1858
  if (!(Array.isArray(parsed) && parsed.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === "string" && (item[1] === null || typeof item[1] === "number")))) throw new Error(`fs history: not a cursor: ${cursor}`);
1544
1859
  return parsed;
1545
1860
  };
1546
- //#endregion
1547
- //#region src/fs-receive.ts
1861
+ // src/fs-receive.ts
1548
1862
  // @license
1549
1863
  /**
1550
1864
  * What a node does with a head that arrived.
@@ -1598,8 +1912,7 @@ var receive = async (head, deps) => {
1598
1912
  }
1599
1913
  return deps.merge(head, relation.base);
1600
1914
  };
1601
- //#endregion
1602
- //#region src/fs-send.ts
1915
+ // src/fs-send.ts
1603
1916
  // @license
1604
1917
  /** Nothing held back. */
1605
1918
  var NOTHING_HELD = /* @__PURE__ */ new Set();
@@ -1667,143 +1980,7 @@ var planAuthoring = (q) => {
1667
1980
  removed: removed.sort()
1668
1981
  };
1669
1982
  };
1670
- //#endregion
1671
- //#region src/fs-ignore.ts
1672
- // @license
1673
- /** Characters whose presence makes a pattern a glob rather than a prefix. */
1674
- var GLOB_CHARS = /[*?/\\]/;
1675
- /**
1676
- * Escapes the regular-expression metacharacters that are NOT glob syntax.
1677
- *
1678
- * `*` and `?` are handled by the translator and must not reach this.
1679
- * @param text - A run of literal characters from a glob.
1680
- * @returns The same text, safe to embed in a regular expression.
1681
- */
1682
- var escapeLiteral = (text) => text.replace(/[.+^${}()|[\]\\\-]/g, "\\$&");
1683
- /**
1684
- * Translates a glob into an anchored, case-insensitive regular expression.
1685
- *
1686
- * `*` and `?` stop at a separator, `**` crosses them. A `**` followed by `/`
1687
- * also matches ZERO directories, so `**\/x` matches `x` at the root as well as
1688
- * at any depth — the one piece of gitignore's behaviour that is not obvious
1689
- * from the characters.
1690
- * @param glob - The pattern, separators already normalised to `/`.
1691
- * @returns A regular expression matching the whole string.
1692
- */
1693
- var globToRegExp = (glob) => {
1694
- let out = "";
1695
- for (let i = 0; i < glob.length; i++) {
1696
- const char = glob[i];
1697
- if (char === "*") {
1698
- if (glob[i + 1] === "*") {
1699
- i++;
1700
- if (glob[i + 1] === "/") {
1701
- out += "(?:[^/]+/)*";
1702
- i++;
1703
- } else out += ".*";
1704
- } else out += "[^/]*";
1705
- } else if (char === "?") out += "[^/]";
1706
- else out += escapeLiteral(char);
1707
- }
1708
- return new RegExp(`^${out}$`, "i");
1709
- };
1710
- /**
1711
- * Normalises a path the way every comparison here expects it.
1712
- *
1713
- * Windows separators become `/`, a leading `./` or `/` goes, and a trailing
1714
- * `/` goes — so one path has one spelling whichever side produced it. The
1715
- * watcher reports `sub\dir\file` on Windows and `sub/dir/file` elsewhere for
1716
- * the same file.
1717
- * @param path - A path relative to the sync root.
1718
- * @returns The normalised form.
1719
- */
1720
- var normalise = (path) => {
1721
- const slashed = path.replace(/\\/g, "/").replace(/^\.\//, "").replace(/^\/+/, "").replace(/\/+$/, "");
1722
- return slashed === "." ? "" : slashed;
1723
- };
1724
- /**
1725
- * Compiles one line of an ignore list.
1726
- * @param pattern - The line, as the user or the product wrote it.
1727
- * @returns The rule, or undefined for a blank line or a `#` comment.
1728
- */
1729
- var compileRule = (pattern) => {
1730
- const trimmed = pattern.trim();
1731
- if (trimmed === "" || trimmed.startsWith("#")) return void 0;
1732
- const negated = trimmed.startsWith("!");
1733
- const body = negated ? trimmed.slice(1) : trimmed;
1734
- if (!negated && !GLOB_CHARS.test(body)) return {
1735
- negated: false,
1736
- dirOnly: false,
1737
- kind: "literal",
1738
- literal: body,
1739
- re: void 0
1740
- };
1741
- const dirOnly = /[/\\]$/.test(body);
1742
- const glob = normalise(body);
1743
- if (glob === "") return void 0;
1744
- return {
1745
- negated,
1746
- dirOnly,
1747
- kind: glob.includes("/") ? "path" : "segment",
1748
- literal: glob,
1749
- re: globToRegExp(glob)
1750
- };
1751
- };
1752
- /**
1753
- * Whether one rule covers a path.
1754
- * @param rule - The compiled rule.
1755
- * @param path - The normalised relative path.
1756
- * @param segments - That path, split on `/`.
1757
- * @param isDirectory - True, false, or undefined when the caller cannot say.
1758
- * @returns True when the rule matches.
1759
- */
1760
- var ruleMatches = (rule, path, segments, isDirectory) => {
1761
- if (rule.kind === "literal") return segments.some((segment) => segment === rule.literal || segment.startsWith(rule.literal));
1762
- const re = rule.re;
1763
- if (rule.kind === "segment") {
1764
- const last = segments.length - 1;
1765
- return segments.some((segment, index) => {
1766
- if (!re.test(segment)) return false;
1767
- if (!rule.dirOnly) return true;
1768
- return index < last || isDirectory !== false;
1769
- });
1770
- }
1771
- if (re.test(path) && !(rule.dirOnly && isDirectory === false)) return true;
1772
- let ancestor = "";
1773
- for (const segment of segments.slice(0, -1)) {
1774
- ancestor = ancestor === "" ? segment : `${ancestor}/${segment}`;
1775
- if (re.test(ancestor)) return true;
1776
- }
1777
- return false;
1778
- };
1779
- /**
1780
- * Compiles an ignore list into a matcher.
1781
- *
1782
- * **Order matters, and the LAST match decides** — the gitignore rule, and the
1783
- * only one under which `!` can mean anything: `['*.log', '!keep.log']` keeps
1784
- * `keep.log` and `['!keep.log', '*.log']` does not. One caveat inherited with
1785
- * the semantics: the scanner does not descend into an ignored directory, so a
1786
- * `!` line cannot rescue a file inside one.
1787
- * @param patterns - The ignore list, in the order it was written.
1788
- * @returns A matcher over those patterns.
1789
- */
1790
- var compileIgnore = (patterns) => {
1791
- const rules = [];
1792
- for (const pattern of patterns ?? []) {
1793
- const rule = compileRule(pattern);
1794
- if (rule !== void 0) rules.push(rule);
1795
- }
1796
- return { ignores: (relativePath, isDirectory) => {
1797
- const path = normalise(relativePath);
1798
- if (path === "") return false;
1799
- const segments = path.split("/").filter((s) => s !== "");
1800
- let ignored = false;
1801
- for (const rule of rules) if (ruleMatches(rule, path, segments, isDirectory)) ignored = !rule.negated;
1802
- return ignored;
1803
- } };
1804
- };
1805
- //#endregion
1806
- //#region src/fs-scanner.ts
1983
+ // src/fs-scanner.ts
1807
1984
  // @license
1808
1985
  /**
1809
1986
  * How often the safety rescan runs.
@@ -1934,6 +2111,10 @@ var FsScanner = class FsScanner {
1934
2111
  this._bs = options.bs || new BsMem();
1935
2112
  this._scanCachePath = options.scanCachePath;
1936
2113
  }
2114
+ /** The ignore list this scanner applies, in order, as it was given. */
2115
+ get ignore() {
2116
+ return this._options.ignore;
2117
+ }
1937
2118
  get tree() {
1938
2119
  return this._tree;
1939
2120
  }
@@ -2244,10 +2425,21 @@ var FsScanner = class FsScanner {
2244
2425
  * Whether the sync never sees a path: the ignore list, as the scan applies
2245
2426
  * it.
2246
2427
  * @param relativePath - Relative to the root, either separator.
2428
+ * @param isDirectory - Whether the path is a directory, when known.
2247
2429
  * @returns `true` when no tree of this folder can hold the path.
2248
2430
  */
2249
- ignores(relativePath) {
2250
- return this._shouldIgnorePath(relativePath);
2431
+ ignores(relativePath, isDirectory) {
2432
+ return this._shouldIgnorePath(relativePath, isDirectory);
2433
+ }
2434
+ /**
2435
+ * Whether a scan leaves a path out: the path, or a directory above it — see
2436
+ * {@link IgnoreMatcher.excludes}.
2437
+ * @param relativePath - Relative to the root, either separator.
2438
+ * @param isDirectory - Whether the path is a directory.
2439
+ * @returns `true` when no scan of this folder holds the path.
2440
+ */
2441
+ excludes(relativePath, isDirectory) {
2442
+ return this._ignoreMatcher.excludes(relativePath, isDirectory);
2251
2443
  }
2252
2444
  async watch() {
2253
2445
  if (this._watcher) throw new Error("Already watching. Call stopWatch() first.");
@@ -2694,8 +2886,7 @@ var FsScanner = class FsScanner {
2694
2886
  ] });
2695
2887
  }
2696
2888
  };
2697
- //#endregion
2698
- //#region src/fs-agent.ts
2889
+ // src/fs-agent.ts
2699
2890
  // @license
2700
2891
  /** Sensible defaults – every operation is bounded */
2701
2892
  var DEFAULT_TIMEOUTS = {
@@ -2752,6 +2943,14 @@ var REPAIR_ACTION = {
2752
2943
  deferred: "blocked",
2753
2944
  blocked: "blocked"
2754
2945
  };
2946
+ /**
2947
+ * Whether two ignore lists are the same list: the same patterns in the same
2948
+ * order — order decides what a `!` line rescues.
2949
+ * @param a - One list.
2950
+ * @param b - The other.
2951
+ * @returns True when they are equal.
2952
+ */
2953
+ var sameList = (a, b) => a.length === b.length && a.every((pattern, i) => pattern === b[i]);
2755
2954
  /** The longest a node waits between two announcements asking for its stamp. */
2756
2955
  var STAMP_ASK_MAX_MS = 3e4;
2757
2956
  /**
@@ -3019,6 +3218,7 @@ var FsAgent = class FsAgent {
3019
3218
  ],
3020
3219
  bs: this._bs
3021
3220
  });
3221
+ this._ignoreOnRecord = this._scanner.ignore;
3022
3222
  this._adapter = new FsBlobAdapter(this._bs);
3023
3223
  }
3024
3224
  /**
@@ -3160,8 +3360,10 @@ var FsAgent = class FsAgent {
3160
3360
  * @param conflicted - Paths edited here while away and changed elsewhere.
3161
3361
  * @param copies - Where each moved file went, `path → name`; a path the
3162
3362
  * join could not move has no entry.
3363
+ * @param why - `away`: the machine joined the network; `ignore`: it sees
3364
+ * paths again that its ignore list had left out.
3163
3365
  */
3164
- _signalJoinOutcome(recovered, conflicted, copies) {
3366
+ _signalJoinOutcome(recovered, conflicted, copies, why = "away") {
3165
3367
  if (recovered.length > 0) this._signal({
3166
3368
  kind: "join/recovered",
3167
3369
  paths: recovered,
@@ -3176,7 +3378,7 @@ var FsAgent = class FsAgent {
3176
3378
  copies,
3177
3379
  action: "review",
3178
3380
  decidedBy: "chain",
3179
- detail: `${conflicted.length} file(s) were edited on this machine while it was away and also changed on the network; both versions were kept`
3381
+ detail: why === "away" ? `${conflicted.length} file(s) were edited on this machine while it was away and also changed on the network; both versions were kept` : `${conflicted.length} file(s) this machine had left out of the sync differ from the network's; both versions were kept`
3180
3382
  });
3181
3383
  }
3182
3384
  /**
@@ -3438,8 +3640,12 @@ var FsAgent = class FsAgent {
3438
3640
  this._restoreImpossible.push(meta.relativePath);
3439
3641
  return;
3440
3642
  }
3643
+ if (this._leavesOut(meta, isOwnRoot)) return;
3441
3644
  const filePath = join(targetPath, meta.relativePath);
3442
- await this._makeRoomFor(filePath, "file");
3645
+ if (!await this._makeRoomFor(filePath, "file", isOwnRoot ? meta.relativePath : void 0)) {
3646
+ this._restoreImpossible.push(meta.relativePath);
3647
+ return;
3648
+ }
3443
3649
  /* v8 ignore else -- @preserve */
3444
3650
  if (meta.blobId) {
3445
3651
  if (await this._alreadyOnDisk(filePath, meta, isOwnRoot)) {
@@ -3513,8 +3719,12 @@ var FsAgent = class FsAgent {
3513
3719
  this._restoreImpossible.push(meta.relativePath);
3514
3720
  return;
3515
3721
  }
3722
+ if (this._leavesOut(meta, isOwnRoot)) return;
3516
3723
  const dirPath = meta.relativePath === "." ? targetPath : join(targetPath, meta.relativePath);
3517
- if (meta.relativePath !== ".") await this._makeRoomFor(dirPath, "directory");
3724
+ if (meta.relativePath !== "." && !await this._makeRoomFor(dirPath, "directory", isOwnRoot ? meta.relativePath : void 0)) {
3725
+ this._restoreImpossible.push(meta.relativePath);
3726
+ return;
3727
+ }
3518
3728
  await mkdir(dirPath, { recursive: true });
3519
3729
  /* v8 ignore else -- @preserve */
3520
3730
  if (treeNode.children && Array.isArray(treeNode.children)) {
@@ -3606,7 +3816,10 @@ var FsAgent = class FsAgent {
3606
3816
  * followed to decide what to remove.
3607
3817
  * @param path - Where the node is to be written.
3608
3818
  * @param want - What the tree says should be there.
3609
- * @returns Whether something had to be removed.
3819
+ * @param relativePath - The path in the folder, when restoring into this
3820
+ * node's own: an entry there this node ignores is never removed.
3821
+ * @returns Whether the place is free for the node now; `false` when an
3822
+ * entry this node ignores holds it.
3610
3823
  */
3611
3824
  /**
3612
3825
  * Whether a path the prune is about to delete is actually the expected file
@@ -3630,11 +3843,27 @@ var FsAgent = class FsAgent {
3630
3843
  if (same) console.warn(`${this._tag} restore: kept "${fullPath}" — the tree spells it "${expected}" and this filesystem treats them as one file`);
3631
3844
  return same;
3632
3845
  }
3633
- async _makeRoomFor(path, want) {
3846
+ /**
3847
+ * Whether a restore leaves a node out: what this node does not see, it does
3848
+ * not write into its folder — a directory with everything below it. Another
3849
+ * node's version of such a path is carried in its edits, never put on its
3850
+ * disk. Anywhere else a tree is just a tree.
3851
+ * @param meta - The node's meta.
3852
+ * @param isOwnRoot - Whether the restore writes into this node's folder.
3853
+ * @returns True when the node is not to be written.
3854
+ */
3855
+ _leavesOut(meta, isOwnRoot) {
3856
+ return isOwnRoot && meta.relativePath !== "." && this._scanner.ignores(meta.relativePath, meta.type === "directory");
3857
+ }
3858
+ async _makeRoomFor(path, want, relativePath) {
3634
3859
  const existing = await lstat(path).catch(() => void 0);
3635
- if (existing === void 0) return false;
3860
+ if (existing === void 0) return true;
3636
3861
  const isDir = existing.isDirectory();
3637
- if (isDir === (want === "directory")) return false;
3862
+ if (isDir === (want === "directory")) return true;
3863
+ if (relativePath !== void 0 && this._scanner.excludes(relativePath, isDir)) {
3864
+ console.warn(`${this._tag} restore: "${path}" is a ${isDir ? "directory" : "file"} this node ignores and the tree says ${want} — left as it is`);
3865
+ return false;
3866
+ }
3638
3867
  await rm(path, {
3639
3868
  recursive: true,
3640
3869
  force: true
@@ -3969,6 +4198,26 @@ var FsAgent = class FsAgent {
3969
4198
  * restart the floors judge what is gone afresh, as before.
3970
4199
  */
3971
4200
  _heldBack = /* @__PURE__ */ new Set();
4201
+ /**
4202
+ * The own head's nodes at the paths this node does not see — see
4203
+ * `fs-carry.ts`. Carried into every edit it authors; an apply neither writes
4204
+ * nor deletes them. Empty while the head names nothing this node ignores.
4205
+ */
4206
+ _carried = /* @__PURE__ */ new Map();
4207
+ /**
4208
+ * Paths this node sees again since a pattern left its ignore list, whose
4209
+ * version the own head holds is not in the folder yet. Carried until it is —
4210
+ * see {@link FsAgent._uncover}.
4211
+ */
4212
+ _uncovered = /* @__PURE__ */ new Set();
4213
+ /** A restart found its ignore list changed, and `_uncover` has not run. */
4214
+ _uncoverDue = false;
4215
+ /**
4216
+ * The ignore list the state file records: the one the folder is in step
4217
+ * with. It becomes the scanner's list once nothing a change of the list
4218
+ * uncovered is still missing.
4219
+ */
4220
+ _ignoreOnRecord = [];
3972
4221
  /** Every chain entry's stamp, as this node learned it. */
3973
4222
  _stamps;
3974
4223
  /** The route this agent syncs, once a sync started. */
@@ -4180,9 +4429,25 @@ var FsAgent = class FsAgent {
4180
4429
  * @returns The head, or `undefined`.
4181
4430
  */
4182
4431
  _persistedHead() {
4432
+ const state = this._persistedState();
4433
+ return typeof state?.ownHead === "string" && state.ownHead !== "" ? state.ownHead : void 0;
4434
+ }
4435
+ /**
4436
+ * The ignore list `.fsagent-state.json` records, if it records one — the
4437
+ * list the folder was in step with when this node last ran.
4438
+ * @returns The list, or `undefined`.
4439
+ */
4440
+ _persistedIgnore() {
4441
+ const ignore = this._persistedState()?.ignore;
4442
+ return Array.isArray(ignore) && ignore.every((pattern) => typeof pattern === "string") ? ignore : void 0;
4443
+ }
4444
+ /**
4445
+ * `.fsagent-state.json`, read.
4446
+ * @returns What it holds, or `undefined` when it cannot be read.
4447
+ */
4448
+ _persistedState() {
4183
4449
  try {
4184
- const state = JSON.parse(readFileSync(join(this._rootPath, AGENT_STATE_FILE), "utf-8"));
4185
- return typeof state?.ownHead === "string" && state.ownHead !== "" ? state.ownHead : void 0;
4450
+ return JSON.parse(readFileSync(join(this._rootPath, AGENT_STATE_FILE), "utf-8"));
4186
4451
  } catch {
4187
4452
  return;
4188
4453
  }
@@ -4191,21 +4456,43 @@ var FsAgent = class FsAgent {
4191
4456
  * Makes `head` this node's head, and remembers it across a restart.
4192
4457
  * @param head - The chain entry.
4193
4458
  * @param content - The tree it names, `path → blob`.
4459
+ * @param carried - Its nodes at the paths this node does not see.
4194
4460
  */
4195
- _setOwn(head, content) {
4461
+ _setOwn(head, content, carried) {
4196
4462
  this._ownHead = head;
4197
4463
  this._ownContent = content;
4464
+ this._carried = carried;
4465
+ for (const path of this._uncovered) if (!content.has(path)) this._uncovered.delete(path);
4466
+ if (this._uncovered.size === 0 && !this._uncoverDue) this._ignoreOnRecord = this._scanner.ignore;
4198
4467
  this._partiallyApplied.clear();
4199
4468
  this._writeState();
4200
4469
  }
4201
- /** Writes {@link AGENT_STATE_FILE}: the own head and the stamp epochs. */
4470
+ /**
4471
+ * What a head's tree holds at the paths this node does not see: those its
4472
+ * ignore list leaves out, and those it sees again and does not hold yet.
4473
+ * @param tree - The tree.
4474
+ * @returns The nodes, by path.
4475
+ */
4476
+ _carriedOf(tree) {
4477
+ const carried = carriedNodes(tree, (path, isDirectory) => this._scanner.ignores(path, isDirectory));
4478
+ if (this._uncovered.size > 0) for (const node of tree.trees.values()) {
4479
+ const path = node.meta.relativePath;
4480
+ if (this._uncovered.has(path)) carried.set(path, node);
4481
+ }
4482
+ return carried;
4483
+ }
4484
+ /**
4485
+ * Writes {@link AGENT_STATE_FILE}: the own head, the stamp epochs, and the
4486
+ * ignore list the folder is in step with.
4487
+ */
4202
4488
  _writeState() {
4203
4489
  const stampEpochs = this._stamps.epochs;
4204
4490
  this._writtenEpochs = JSON.stringify(stampEpochs);
4205
4491
  try {
4206
4492
  atomicWriteFileSync(join(this._rootPath, AGENT_STATE_FILE), JSON.stringify({
4207
4493
  ownHead: this._ownHead,
4208
- stampEpochs
4494
+ stampEpochs,
4495
+ ignore: this._ignoreOnRecord
4209
4496
  }));
4210
4497
  } catch (err) {
4211
4498
  this._writeSyncError("state/write", err);
@@ -4264,12 +4551,14 @@ var FsAgent = class FsAgent {
4264
4551
  this._announceOwn();
4265
4552
  }
4266
4553
  /**
4267
- * Authors an edit for the folder as `tree` describes it, if it moved past
4268
- * the own head and the edit is honest — see `planAuthoring`.
4269
- * @param tree - The folder, as just scanned.
4554
+ * Authors an edit for the folder as `scanned` describes it, if it moved past
4555
+ * the own head and the edit is honest — see `planAuthoring`. The paths this
4556
+ * node does not see are carried as the own head holds them.
4557
+ * @param scanned - The folder, as just scanned.
4270
4558
  */
4271
- async _author(tree) {
4559
+ async _author(scanned) {
4272
4560
  if (this._joinWait || !this._route || !this._chain) return;
4561
+ const { tree, carried } = graftTree(scanned, this._carried);
4273
4562
  const folder = this._getFileContentMap(tree);
4274
4563
  if (this._ownHead === void 0) {
4275
4564
  if (folder.size === 0) return;
@@ -4278,14 +4567,16 @@ var FsAgent = class FsAgent {
4278
4567
  treeRef,
4279
4568
  previous: []
4280
4569
  });
4281
- this._setOwn(root.head, folder);
4570
+ this._setOwn(root.head, folder, carried);
4282
4571
  this._watched.clear();
4283
4572
  this._announceOwn();
4284
4573
  return;
4285
4574
  }
4575
+ const head = this._partiallyApplied.size === 0 ? this._ownContent : new Map([...this._ownContent, ...this._partiallyApplied]);
4576
+ const seen = (content) => carried.size === 0 ? content : new Map([...content].filter(([path]) => !carried.has(path)));
4286
4577
  const plan = planAuthoring({
4287
- folder,
4288
- head: this._partiallyApplied.size === 0 ? this._ownContent : new Map([...this._ownContent, ...this._partiallyApplied]),
4578
+ folder: seen(folder),
4579
+ head: seen(head),
4289
4580
  watched: this._watched,
4290
4581
  minFiles: 100,
4291
4582
  maxRatio: MASS_DELETE_MAX_RATIO,
@@ -4310,7 +4601,7 @@ var FsAgent = class FsAgent {
4310
4601
  removed: plan.removed,
4311
4602
  previous: [this._ownHead]
4312
4603
  });
4313
- this._setOwn(entry.head, folder);
4604
+ this._setOwn(entry.head, folder, carried);
4314
4605
  this._watched.clear();
4315
4606
  this._announceOwn();
4316
4607
  }
@@ -4344,8 +4635,16 @@ var FsAgent = class FsAgent {
4344
4635
  const persisted = this._persistedHead();
4345
4636
  const resumed = persisted !== void 0 && await this._treeOf(persisted);
4346
4637
  if (resumed) {
4347
- this._setOwn(persisted, this._getFileContentMap(resumed.tree));
4348
- await this._exclusive(() => this._author(initial));
4638
+ const recorded = this._persistedIgnore();
4639
+ if (recorded !== void 0 && !sameList(recorded, this._scanner.ignore)) {
4640
+ this._ignoreOnRecord = recorded;
4641
+ this._uncoverDue = true;
4642
+ }
4643
+ this._setOwn(persisted, this._getFileContentMap(resumed.tree), this._carriedOf(resumed.tree));
4644
+ await this._exclusive(async () => {
4645
+ const moved = this._uncoverDue && await this._writing(() => this._uncover(persisted, resumed.tree, initial));
4646
+ await this._author(moved ? await this._scanner.scanFresh() : initial);
4647
+ });
4349
4648
  this._announceOwn();
4350
4649
  } else if (this._joinWaitMs > 0) this._startJoinWait();
4351
4650
  else await this._exclusive(() => this._author(initial));
@@ -4421,11 +4720,88 @@ var FsAgent = class FsAgent {
4421
4720
  for (const path of plan.conflict) await this._setAside(path, joinCopyName(path, Date.now(), taken), copies);
4422
4721
  this._signalJoinOutcome(plan.recover, plan.conflict, copies);
4423
4722
  await this.restore(joined.tree, void 0, { cleanTarget: false });
4424
- this._setOwn(head, headContent);
4723
+ this._setOwn(head, headContent, this._carriedOf(joined.tree));
4425
4724
  await this._author(await this._scanner.scanFresh());
4426
4725
  this._announceOwn();
4427
4726
  }
4428
4727
  /**
4728
+ * Joins the paths this node sees again: a pattern left its ignore list
4729
+ * since it last ran.
4730
+ *
4731
+ * While a path was ignored, this node neither wrote it nor deleted it, so
4732
+ * the folder can lack what the head holds there, or hold a version of its
4733
+ * own that never went anywhere. Authored as they stand, the first would
4734
+ * delete the network's files and the second overwrite them. So these paths
4735
+ * are joined as a joining folder is (`planJoin`): a version of this node's
4736
+ * own is set aside as a copy, one the history removed goes to
4737
+ * {@link RECOVERED_DIR}, one the history never named is new work — and the
4738
+ * head's version is written, and carried until it is there.
4739
+ * @param head - The own head.
4740
+ * @param headTree - Its tree.
4741
+ * @param folderTree - The folder, as just scanned.
4742
+ * @returns Whether anything in the folder was moved aside.
4743
+ */
4744
+ async _uncover(head, headTree, folderTree) {
4745
+ const was = compileIgnore(this._ignoreOnRecord);
4746
+ const seenAgain = (content) => new Map([...content].filter(([path, value]) => !this._carried.has(path) && was.excludes(path, value === "<dir>")));
4747
+ const folder = this._getFileContentMap(folderTree);
4748
+ const inHead = seenAgain(this._ownContent);
4749
+ const inFolder = seenAgain(folder);
4750
+ let changed = false;
4751
+ if (inHead.size > 0 || inFolder.size > 0) {
4752
+ const walk = await this._chain.collectRemovals(head, void 0).catch(() => void 0);
4753
+ const plan = planJoin({
4754
+ haveHead: true,
4755
+ head: inHead,
4756
+ folder: inFolder,
4757
+ removedEver: new Set(walk?.complete ? walk.removed : [])
4758
+ });
4759
+ const taken = /* @__PURE__ */ new Set([...folder.keys(), ...this._ownContent.keys()]);
4760
+ const copies = {};
4761
+ for (const path of plan.recover) await this._setAside(path, `${RECOVERED_DIR}/${recoveredName(path, taken)}`, copies);
4762
+ for (const path of plan.conflict) await this._setAside(path, joinCopyName(path, Date.now(), taken), copies);
4763
+ this._signalJoinOutcome(plan.recover, plan.conflict, copies, "ignore");
4764
+ for (const path of [...plan.write, ...plan.conflict]) this._uncovered.add(path);
4765
+ this._carried = this._carriedOf(headTree);
4766
+ changed = plan.recover.length + plan.conflict.length > 0;
4767
+ }
4768
+ this._uncoverDue = false;
4769
+ if (this._uncovered.size === 0) this._ignoreOnRecord = this._scanner.ignore;
4770
+ this._writeState();
4771
+ return changed;
4772
+ }
4773
+ /**
4774
+ * Writes the head's version of every path `_uncover` is waiting for that is
4775
+ * not in the folder — and stops carrying each one that is, whichever
4776
+ * version: a file somebody saved there meanwhile is their work, and the
4777
+ * next edit says so.
4778
+ *
4779
+ * Asked again with every head this node hears, so a version that could not
4780
+ * be fetched — this node started offline — arrives once it can be.
4781
+ */
4782
+ async _takeUncovered() {
4783
+ if (this._uncovered.size === 0) return;
4784
+ const there = (path) => lstat(join(this._rootPath, ...path.split("/"))).then(() => true, () => false);
4785
+ const missing = [];
4786
+ for (const path of this._uncovered) if (!await there(path)) missing.push(path);
4787
+ if (missing.length > 0) try {
4788
+ const own = await this._treeOf(this._ownHead);
4789
+ if (!own) throw new Error("the own head cannot be read");
4790
+ await this._restorePaths(own.tree, missing);
4791
+ } catch (err) {
4792
+ this._writeSyncError("uncover", err);
4793
+ }
4794
+ const arrived = /* @__PURE__ */ new Set();
4795
+ for (const path of this._uncovered) if (await there(path)) arrived.add(path);
4796
+ if (arrived.size === 0) return;
4797
+ for (const path of arrived) this._uncovered.delete(path);
4798
+ this._carried = new Map([...this._carried].filter(([path]) => !arrived.has(path)));
4799
+ if (this._uncovered.size === 0) {
4800
+ this._ignoreOnRecord = this._scanner.ignore;
4801
+ this._writeState();
4802
+ }
4803
+ }
4804
+ /**
4429
4805
  * Hears a head — from an announcement, a bootstrap or a state beacon.
4430
4806
  * @param head - The head.
4431
4807
  * @param stamp - The stamp it arrived with, if any.
@@ -4540,7 +4916,10 @@ var FsAgent = class FsAgent {
4540
4916
  const chain = this._chain;
4541
4917
  return {
4542
4918
  ownHead: () => this._ownHead,
4543
- flushLocal: async () => this._author(await this._scanner.scanFresh()),
4919
+ flushLocal: async () => {
4920
+ await this._takeUncovered();
4921
+ await this._author(await this._scanner.scanFresh());
4922
+ },
4544
4923
  relate: (ours, theirs) => chain.relate(ours, theirs),
4545
4924
  treeRefOf: async (head) => (await chain.entry(head))?.treeRef,
4546
4925
  applyBehind: (head) => this._applyBehind(head),
@@ -4562,7 +4941,7 @@ var FsAgent = class FsAgent {
4562
4941
  * @param head - The head.
4563
4942
  */
4564
4943
  async _adopt(head) {
4565
- this._setOwn(head, this._ownContent);
4944
+ this._setOwn(head, this._ownContent, this._carried);
4566
4945
  }
4567
4946
  /**
4568
4947
  * Applies a head that descends from the own one: writes what it changed,
@@ -4584,12 +4963,13 @@ var FsAgent = class FsAgent {
4584
4963
  const theirs = await this._treeOf(head);
4585
4964
  if (!theirs) return "refused";
4586
4965
  const target = this._getFileContentMap(theirs.tree);
4587
- const applied = await this._applyContent(target, (paths) => this._restorePaths(theirs.tree, paths));
4966
+ const carried = this._carriedOf(theirs.tree);
4967
+ const applied = await this._applyContent(target, (paths) => this._restorePaths(theirs.tree, paths), carried);
4588
4968
  if (applied === "moved") {
4589
4969
  this._receiveAgain(head);
4590
4970
  return "refused";
4591
4971
  }
4592
- this._setOwn(head, target);
4972
+ this._setOwn(head, target, carried);
4593
4973
  if (applied === "kept") await this._author(await this._scanner.scanFresh());
4594
4974
  return "applied";
4595
4975
  }
@@ -4601,22 +4981,33 @@ var FsAgent = class FsAgent {
4601
4981
  * — content `target` holds nowhere else — is not made. Everything else is,
4602
4982
  * and the files kept become this node's work, so the folder never holds a
4603
4983
  * state the chain does not describe.
4984
+ * The paths this node does not see are neither written nor deleted, and
4985
+ * the guard counts only what the folder holds.
4604
4986
  * @param target - Where the folder should end up, `path → blob`.
4605
4987
  * @param write - Writes the given paths' `target` versions.
4988
+ * @param carried - `target`'s nodes at the paths this node does not see.
4606
4989
  * @returns `applied`; `kept` when the guard kept files `target` lacks;
4607
4990
  * `moved` when the folder had moved past the own head.
4608
4991
  */
4609
- async _applyContent(target, write) {
4992
+ async _applyContent(target, write, carried) {
4610
4993
  const own = this._ownContent;
4611
4994
  const landed = this._partiallyApplied;
4612
- const writes = [...target.keys()].filter((p) => target.get(p) !== own.get(p) && target.get(p) !== landed.get(p));
4613
- const deletes = [...own.keys()].filter((p) => !target.has(p));
4995
+ const anyCarried = this._carried.size > 0 || carried.size > 0;
4996
+ const seen = (p) => !anyCarried || !this._carried.has(p) && !carried.has(p);
4997
+ const writes = [...target.keys()].filter((p) => target.get(p) !== own.get(p) && target.get(p) !== landed.get(p) && seen(p));
4998
+ const deletes = [...own.keys()].filter((p) => !target.has(p) && seen(p));
4614
4999
  const isFile = (v) => v !== void 0 && v !== "<dir>";
4615
- const held = [...own.values()].filter(isFile).length;
5000
+ const filesIn = (content) => {
5001
+ const blobs = [];
5002
+ for (const [p, v] of content) if (isFile(v) && seen(p)) blobs.push(v);
5003
+ return blobs;
5004
+ };
5005
+ const held = filesIn(own).length;
4616
5006
  const deletedFiles = deletes.filter((p) => isFile(own.get(p)));
4617
- const stillThere = new Set([...target.values()].filter(isFile));
5007
+ const targetFiles = filesIn(target);
5008
+ const stillThere = new Set(targetFiles);
4618
5009
  const lost = deletedFiles.filter((p) => !stillThere.has(own.get(p)));
4619
- const keep = new Set(lost.length > 100 && lost.length / held > .3 || lost.length > 0 && held > 10 && [...target.values()].filter(isFile).length <= 10 ? lost : []);
5010
+ const keep = new Set(lost.length > 100 && lost.length / held > .3 || lost.length > 0 && held > 10 && targetFiles.length <= 10 ? lost : []);
4620
5011
  const deleting = deletes.filter((p) => !keep.has(p));
4621
5012
  if (!await this._unchangedSinceOwn([...writes, ...deleting])) return "moved";
4622
5013
  if (writes.length > 0) try {
@@ -4760,6 +5151,7 @@ var FsAgent = class FsAgent {
4760
5151
  this._deferral = key;
4761
5152
  return "deferred";
4762
5153
  }
5154
+ const theirCarried = this._carriedOf(theirTree.tree);
4763
5155
  if (await this._applyContent(outcome.merged, async (paths) => {
4764
5156
  const fromTheirs = paths.filter((p) => outcome.merged.get(p) === theirContent.get(p));
4765
5157
  if (fromTheirs.length > 0) await this._restorePaths(theirTree.tree, fromTheirs);
@@ -4771,11 +5163,11 @@ var FsAgent = class FsAgent {
4771
5163
  const st = await stat(full);
4772
5164
  this._scanner.noteWrite(path, blob, st.size, st.mtime.getTime());
4773
5165
  }
4774
- }) === "moved") {
5166
+ }, theirCarried) === "moved") {
4775
5167
  this._receiveAgain(theirs);
4776
5168
  return "refused";
4777
5169
  }
4778
- const merged = await this._scanner.scanFresh();
5170
+ const { tree: merged, carried } = graftTree(await this._scanner.scanFresh(), await this._mergeCarried(outcome.merged, theirContent, theirCarried));
4779
5171
  const mergedContent = this._getFileContentMap(merged);
4780
5172
  const treeRef = await this._storeTree(merged);
4781
5173
  const touched = [.../* @__PURE__ */ new Set([
@@ -4795,7 +5187,7 @@ var FsAgent = class FsAgent {
4795
5187
  _hash: ""
4796
5188
  })._hash}`
4797
5189
  });
4798
- this._setOwn(entry.head, mergedContent);
5190
+ this._setOwn(entry.head, mergedContent, carried);
4799
5191
  for (const conflict of outcome.conflicts) this._signal({
4800
5192
  kind: conflict.kind,
4801
5193
  paths: [conflict.path],
@@ -4809,6 +5201,31 @@ var FsAgent = class FsAgent {
4809
5201
  return "merged";
4810
5202
  }
4811
5203
  /**
5204
+ * What a merge's result holds at the paths this node does not see: the node
5205
+ * of whichever side's version it kept there — and, for a copy a conflict
5206
+ * made at such a path, a node for the version the copy keeps, which the
5207
+ * merge wrote like any other copy.
5208
+ * @param merged - The merge's result, `path → blob`.
5209
+ * @param theirs - The forked head's content.
5210
+ * @param theirCarried - Its nodes at the paths this node does not see.
5211
+ * @returns The nodes to carry, by path.
5212
+ */
5213
+ async _mergeCarried(merged, theirs, theirCarried) {
5214
+ const ours = this._ownContent;
5215
+ const carried = /* @__PURE__ */ new Map();
5216
+ for (const [path, value] of merged) {
5217
+ const yours = theirCarried.get(path);
5218
+ const mine = this._carried.get(path);
5219
+ if (yours && value === theirs.get(path)) carried.set(path, yours);
5220
+ else if (mine && value === ours.get(path)) carried.set(path, mine);
5221
+ else if (!ours.has(path) && !theirs.has(path) && this._scanner.excludes(path, false)) {
5222
+ const st = await stat(join(this._rootPath, ...path.split("/"))).catch(() => void 0);
5223
+ if (st?.isFile()) carried.set(path, fileNode(path, value, st.size));
5224
+ }
5225
+ }
5226
+ return carried;
5227
+ }
5228
+ /**
4812
5229
  * Hears the network: announcements, the stamps of this node's own, and the
4813
5230
  * hub's state beacon.
4814
5231
  * @param db - The route's database.
@@ -4826,14 +5243,16 @@ var FsAgent = class FsAgent {
4826
5243
  await this._ensureWatching();
4827
5244
  connector.resetReceived?.();
4828
5245
  const generation = ++this._receivers;
5246
+ let listening = true;
4829
5247
  connector.listen(async (ref, _predecessors, info) => {
4830
- this._hear(ref, info?.stamp);
5248
+ if (listening) this._hear(ref, info?.stamp);
4831
5249
  });
4832
5250
  const offStamp = connector.onStamp((ref, stamp) => this._recordStamp(ref, stamp));
4833
5251
  const beacon = (payload) => this._hear(payload?.r, payload?.stamp, true);
4834
5252
  const events = [connector.events.bootstrap, stateBeaconEvent(connector.route.flat)];
4835
5253
  for (const event of events) connector.socket.on(event, beacon);
4836
5254
  return () => {
5255
+ listening = false;
4837
5256
  offStamp();
4838
5257
  for (const event of events) connector.socket.off(event, beacon);
4839
5258
  connector.tearDown();
@@ -4919,8 +5338,7 @@ var FsAgent = class FsAgent {
4919
5338
  return new FsAgent(process.cwd());
4920
5339
  }
4921
5340
  };
4922
- //#endregion
4923
- //#region src/client-server/client-server-setup.ts
5341
+ // src/client-server/client-server-setup.ts
4924
5342
  // @license
4925
5343
  async function createSharedTreeTable(io, treeKey) {
4926
5344
  const db = new Db(io);
@@ -4998,8 +5416,6 @@ async function runClientServerSetup(opts = {}) {
4998
5416
  cleanup
4999
5417
  };
5000
5418
  }
5001
- //#endregion
5002
- //#region src/index.ts
5419
+ // src/index.ts
5003
5420
  // @license
5004
- //#endregion
5005
5421
  export { ATOMIC_TMP_PREFIX, BlobUnavailableError, DiskFullError, FS_EDIT_ACTION, FS_HISTORY_PAGE, FsAgent, FsBlobAdapter, FsDbAdapter, FsEditChain, FsScanner, FsSignals, MassDeleteRefusedError, PartialRestoreError, RestoreIncompleteError, SIGNAL_LOG_FILE, SIGNAL_LOG_MAX, SIGNAL_ONCE_MAX, SIGNAL_PATHS_MAX, SYNC_ERROR_FILE, UnwritablePathError, atomicTmpPath, atomicWriteFile, atomicWriteFileSync, atomicWriteStream, compileIgnore, createFsChainTables, globToRegExp, readFsHistory, readFsStamps, runClientServerSetup, walkFsHistory };