mnfst 0.5.320 → 0.5.321

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.
@@ -623,8 +623,58 @@
623
623
  if (eq(before, order) && !Object.keys(markup || {}).length) return;
624
624
  const d = { kind: 'st-children', region: key(area), parent: parentKey(container, area), order, before, html: markup || {} };
625
625
  if (copies && Object.keys(copies).length) d.copies = copies;
626
+ withIds(d, [...before, ...order.filter(k => k[0] === '~').map(originOf)]);
626
627
  pushDelta(d);
627
628
  }
629
+ // Renames keys through every delta that `pick` selects
630
+ function renameKeys(ren, pick) {
631
+ const enc = (v) => v.replace(/&/g, '&').replace(/"/g, '"'), dec = (v) => v.replace(/"/g, '"').replace(/&/g, '&');
632
+ const arr = (a) => Array.isArray(a) ? a.map(ren) : a;
633
+ log.forEach(d => {
634
+ if (pick && !pick(d)) return;
635
+ ['before', 'order', 'fromBefore', 'toBefore', 'fromOrder', 'toOrder', 'unsure'].forEach(f => { if (d[f]) d[f] = arr(d[f]); });
636
+ ['parent', 'fromParent', 'toParent', 'key', 'path'].forEach(f => { if (typeof d[f] === 'string') d[f] = ren(d[f]); });
637
+ if (d.html) d.html = Object.fromEntries(Object.entries(d.html).map(([k, h]) => [ren(k), typeof h === 'string' ? h.replace(/data-edit-key="([^"]*)"/g, (all, v) => `data-edit-key="${enc(ren(dec(v)))}"`) : h]));
638
+ if (d.copies) d.copies = Object.fromEntries(Object.entries(d.copies).map(([k, v]) => [ren(k), v]));
639
+ });
640
+ }
641
+ // The source identity of each twin a structural edit names, checked after a reload
642
+ // A key told apart from its twins only by position (same tag and first 24 characters)
643
+ const familyOf = (k) => String(k).replace(/#\d+$/, '');
644
+ const ord = (k) => { const m = /#(\d+)$/.exec(k); return m ? +m[1] : 1; };
645
+ const byOrd = (x, y) => ord(x) - ord(y);
646
+ // Where the content recorded at R[i] (a family's content ids by position) now is in F, on
647
+ // evidence of a move only. Same size: another member whose own content changed holds it (a
648
+ // permutation). Members added or removed: everything recorded from i on found again, in order,
649
+ // shifted. In place, not found, or shared with another recorded member: null or [] (positional).
650
+ function movedIn(R, F, i) {
651
+ const v = R[i];
652
+ if (v == null || F[i] == null || F[i] === v || R.some((x, j) => j !== i && x === v)) return null;
653
+ if (F.length === R.length) return F.map((x, j) => j).filter(j => j !== i && F[j] === v && F[j] !== R[j]);
654
+ const to = [];
655
+ for (let d = -i; d < F.length - i; d++) {
656
+ if (!d) continue;
657
+ let ok = true;
658
+ for (let t = i; t < R.length && ok; t++) ok = t + d >= 0 && t + d < F.length && F[t + d] === R[t];
659
+ if (ok) to.push(i + d);
660
+ }
661
+ return to;
662
+ }
663
+ const twinKey = (k) => typeof k === 'string' && k[0] === '@' && (/#\d+$/.test(k) || keyMap(staticAreas()).has(k + '#2'));
664
+ // The content id of each twin an edit names, and of the rest of its family, as the base read them;
665
+ // twins of a file a rebase wrote over unseen are listed as unverifiable instead
666
+ function withIds(d, keys) {
667
+ const ids = {}, unsure = new Set();
668
+ keys.forEach(k => {
669
+ if (!twinKey(k) || ids[k]) return;
670
+ const o = originOf(k), a = areaByKey(decodeURIComponent(o.slice(1, o.indexOf('@', 1)))), f = a && sourceFile(a), m = baseCids && f && baseCids[f];
671
+ if (cidsUnsure.has(familyOf(o))) unsure.add(o);
672
+ else if (m) Object.keys(m).forEach(j => { if (familyOf(j) === familyOf(o)) ids[j] = m[j]; });
673
+ });
674
+ if (Object.keys(ids).length) d.ids = ids;
675
+ if (unsure.size) d.unsure = [...unsure];
676
+ return d;
677
+ }
628
678
  const materialize = (markup, k) => {
629
679
  if (!markup) return null;
630
680
  const t = document.createElement('template');
@@ -669,7 +719,36 @@
669
719
  // their new keys, so the reorder still applies, but only if no structural edit moved,
670
720
  // added or removed them. Otherwise every structural edit of that region goes (the
671
721
  // writer would refuse them), reported with the children that changed.
672
- const first = new Map(), broken = new Map(), renames = new Map();
722
+ const first = new Map(), broken = new Map(), renames = new Map(), remapped = [];
723
+ // Twins: each element a structural edit named must still hold the source content recorded
724
+ const recId = {};
725
+ const cidLike = (v) => typeof v === 'string' && /^[0-9a-f]{12}$/.test(v);
726
+ log.forEach(d => { if (d.ids) Object.entries(d.ids).forEach(([k, v]) => { if (!(k in recId) && cidLike(v)) recId[k] = v; }); });
727
+ const family = familyOf;
728
+ // Positive evidence only. With the family's size unchanged: the recorded content found at
729
+ // another recorded member whose own content changed (a permutation). With members added or
730
+ // removed: everything recorded from this twin on found again, in order, shifted. Content
731
+ // changed in place, not found, or shared with another recorded twin: positional, as before.
732
+ const movedTo = (k, v = recId[k]) => {
733
+ if (!cidLike(v)) return null;
734
+ const Rk = Object.keys(recId).filter(j => family(j) === family(k)).sort(byOrd), i = Rk.indexOf(k);
735
+ if (i < 0) return null;
736
+ const a = areaByKey(keyRegion(k)), m = baseCids && a && baseCids[sourceFile(a)];
737
+ const Fk = Object.keys(m || {}).filter(j => family(j) === family(k)).sort(byOrd);
738
+ const at = movedIn(Rk.map(j => j === k ? v : recId[j]), Fk.map(freshId), i);
739
+ return at && at.map(j => Fk[j]);
740
+ };
741
+ const unsureKeys = new Set(); log.forEach(d => (d.unsure || []).forEach(k => unsureKeys.add(k)));
742
+ const keyRegion = (k) => decodeURIComponent(k.slice(1, k.indexOf('@', 1)));
743
+ const freshId = (k) => typeof k === 'string' && k[0] === '@' && regions.has(keyRegion(k)) && live.has(k) ? cidOf(k) : null;
744
+ // Only removals in this container: the edit names elements, not positions
745
+ const removalsOnly = (region, parent) => log.every(d => {
746
+ if (d.kind === 'st-move') return !((d.from === region && (d.fromParent || '') === parent) || (d.to === region && (d.toParent || '') === parent));
747
+ if ((d.kind !== 'st-order' && d.kind !== 'st-children') || d.region !== region || (d.parent || '') !== parent) return true;
748
+ if (d.kind === 'st-order' || d.order.some(k => k[0] !== '@')) return false;
749
+ let i = 0; for (const k of d.before) if (k === d.order[i]) i++;
750
+ return i === d.order.length;
751
+ });
673
752
  const note = (region, parent, before) => { const k = JSON.stringify([region, parent]); if (!first.has(k) && isStatic(region)) first.set(k, [region, parent, before || []]); };
674
753
  log.forEach(d => {
675
754
  if (d.kind === 'st-order' || d.kind === 'st-children') note(d.region, d.parent, d.before);
@@ -706,6 +785,23 @@
706
785
  if (holders.size === 1) { c = [...holders][0]; renamedParent = c.getAttribute('data-edit-key'); }
707
786
  }
708
787
  const now = c ? staticKeys(c) : [];
788
+ // The twins the edits act on (removed, moved) must still be theirs, judged on evidence only
789
+ const claimed = [...moved(region, parent)].filter(k => typeof k === 'string' && k[0] === '@');
790
+ const unverifiable = claimed.filter(k => unsureKeys.has(k));
791
+ const swapped = claimed.filter(k => { const t = movedTo(k); return t && t.length; });
792
+ if (unverifiable.length || swapped.length) {
793
+ // Every moved twin found again exactly once, among those that moved: remap a pure delete
794
+ const evidence = Object.keys(recId).filter(k => family(k) && before.includes(k) && (movedTo(k) || []).length);
795
+ let map = !unverifiable.length && !renamedParent && now.join('\n') === before.join('\n') && removalsOnly(region, parent) ? new Map() : null;
796
+ if (map) for (const k of evidence) {
797
+ const at = movedTo(k).filter(j => evidence.includes(j));
798
+ if (at.length !== 1) { map = null; break; }
799
+ map.set(k, at[0]);
800
+ }
801
+ if (map && new Set(map.values()).size === evidence.length) { remapped.push([region, parent, now, map]); return; }
802
+ broken.set(region, [...(broken.get(region) || []), { container: parent, changed: [...new Set([...swapped, ...unverifiable])].map(k => { const l = k.slice(k.indexOf('@', 1) + 1); return { was: l, now: l }; }) }]);
803
+ return;
804
+ }
709
805
  if (c && now.join('\n') === before.join('\n') && !renamedParent) return;
710
806
  const changed = [];
711
807
  before.forEach((k, i) => { if (now[i] !== k) changed.push({ was: k, now: now[i] ?? null }); });
@@ -729,6 +825,48 @@
729
825
  renames.set(region, m);
730
826
  } else broken.set(region, [...(broken.get(region) || []), { container: parent, changed: changed.map(x => ({ was: x.was && tagOf(x.was) && x.was.slice(x.was.indexOf('@', 1) + 1), now: x.now && x.now.slice(x.now.indexOf('@', 1) + 1) })) }]);
731
827
  });
828
+ // A copy names its source element by key: that twin must still be the one copied
829
+ const copyRegions = new Map();
830
+ log.forEach(d => {
831
+ const r = d.kind === 'st-move' ? d.to : d.region;
832
+ [d.order, d.toOrder, d.fromOrder, d.before, Object.keys(d.html || {})].forEach(a => Array.isArray(a) && a.forEach(k => {
833
+ if (typeof k !== 'string' || k[0] !== '~') return;
834
+ const o = originOf(k); if (!copyRegions.has(o)) copyRegions.set(o, new Set()); copyRegions.get(o).add(r);
835
+ }));
836
+ });
837
+ const copyMap = new Map();
838
+ copyRegions.forEach((rs, o) => {
839
+ if (!regions.has(keyRegion(o))) return;
840
+ const t = unsureKeys.has(o) ? null : movedTo(o);
841
+ if (t && !t.length) return;
842
+ if (t && t.length === 1 && live.has(t[0])) { copyMap.set(o, t[0]); return; }
843
+ if (!t && !unsureKeys.has(o)) return;
844
+ const l = o.slice(o.indexOf('@', 1) + 1);
845
+ rs.forEach(r => { if (isStatic(r)) broken.set(r, [...(broken.get(r) || []), { container: '', changed: [{ was: l, now: l }], copy: true }]); });
846
+ });
847
+ if (copyMap.size) {
848
+ const ren = (k) => typeof k === 'string' && k[0] === '~' && copyMap.has(originOf(k)) ? k.slice(0, k.length - originOf(k).length) + copyMap.get(originOf(k)) : k;
849
+ renameKeys(ren, (d) => !broken.has(d.kind === 'st-move' ? d.to : d.region));
850
+ ver++;
851
+ }
852
+ // Remapped twins: removals name the element found again; its text edits follow it (re-checked below)
853
+ remapped.forEach(([region, parent, now, map]) => {
854
+ if (broken.has(region)) return;
855
+ const ren = (k) => typeof k === 'string' && map.has(k) ? map.get(k) : k;
856
+ const enc = (v) => v.replace(/&/g, '&amp;').replace(/"/g, '&quot;'), dec = (v) => v.replace(/&quot;/g, '"').replace(/&amp;/g, '&');
857
+ let cur = now.slice();
858
+ log.forEach(d => {
859
+ if (d.kind === 'st-children' && d.region === region && (d.parent || '') === parent) {
860
+ const out = d.before.filter(k => !d.order.includes(k)).map(ren);
861
+ d.before = cur.slice(); cur = cur.filter(k => !out.includes(k)); d.order = cur.slice();
862
+ if (d.html) d.html = Object.fromEntries(Object.entries(d.html).map(([k, h]) => [ren(k), typeof h === 'string' ? h.replace(/data-edit-key="([^"]*)"/g, (all, v) => `data-edit-key="${enc(ren(dec(v)))}"`) : h]));
863
+ }
864
+ if (d.ids && d.region === region) d.ids = Object.fromEntries(Object.entries(d.ids).map(([k, v]) => [ren(k), v]));
865
+ if (d.kind === 'st-node' && d.region === region && typeof d.path === 'string') d.path = ren(d.path);
866
+ if (d.kind === 'lock' && d.region === region) d.key = ren(d.key);
867
+ });
868
+ ver++;
869
+ });
732
870
  // Renamed children keep their place in every structural edit (their own text edits stay conflicts)
733
871
  renames.forEach((m, region) => {
734
872
  if (broken.has(region)) return;
@@ -757,9 +895,13 @@
757
895
  });
758
896
  const structural = (d) => ((d.kind === 'st-order' || d.kind === 'st-children') && broken.has(d.region)) || (d.kind === 'st-move' && (broken.has(d.from) || broken.has(d.to)))
759
897
  || (d.kind === 'st-node' && broken.has(d.region) && typeof d.path === 'string' && d.path[0] === '~');
760
- const gone = (d) => (d.kind === 'st-node' && typeof d.path === 'string' && d.path[0] === '@' && isStatic(d.region) && !live.has(d.path)) || structural(d);
898
+ // A twin's text edit: on evidence its element moved (or it cannot be verified), reported
899
+ const movedTwin = (d) => (d.unsure || []).includes(d.path) || (movedTo(d.path, d.id) || []).length > 0;
900
+ const gone = (d) => (d.kind === 'st-node' && typeof d.path === 'string' && d.path[0] === '@' && isStatic(d.region) && (!live.has(d.path) || movedTwin(d))) || structural(d);
761
901
  log.forEach((d, i) => { if (gone(d) && i < cursor && d.kind === 'st-node' && d.path[0] === '@') lost.push(d); });
762
- if (!log.some(gone)) { if (renames.size) saveState(); return []; }
902
+ // What survives now applies to this source: its twins' ids are this source's
903
+ const refreshIds = () => log.forEach(d => { if (d.ids) Object.keys(d.ids).forEach(k => { const f = freshId(k); if (f) d.ids[k] = f; }); });
904
+ if (!log.some(gone)) { refreshIds(); if (renames.size || remapped.length || copyMap.size || log.some(d => d.ids)) saveState(); return []; }
763
905
  const latest = new Map();
764
906
  lost.forEach(d => latest.set(d.path + '|' + d.prop, d));
765
907
  const label = (k) => typeof k === 'string' ? originOf(k).slice(originOf(k).indexOf('@', 1) + 1) : '';
@@ -769,10 +911,11 @@
769
911
  // and every copy it made, with the copy's markup and the text typed into it
770
912
  broken.forEach((containers, region) => {
771
913
  const deltas = log.filter((d, i) => i < cursor && structural(d) && (d.region === region || d.from === region || d.to === region));
772
- const movedKeys = new Set(), copies = [];
914
+ const movedKeys = new Set(), deleted = new Set(), copies = [];
773
915
  deltas.forEach(d => {
774
916
  if (d.kind === 'st-move') movedKeys.add(d.key);
775
917
  if (d.kind === 'st-order' || d.kind === 'st-children') moved(region, d.parent || '').forEach(k => movedKeys.add(k));
918
+ if (d.kind === 'st-children') d.before.forEach(k => { if (k[0] === '@' && !d.order.includes(k)) deleted.add(k); });
776
919
  if (d.kind === 'st-children' && d.html) Object.entries(d.html).forEach(([k, h]) => {
777
920
  if (k[0] !== '~') return;
778
921
  const t = document.createElement('template'); t.innerHTML = h;
@@ -781,17 +924,25 @@
781
924
  });
782
925
  });
783
926
  const changed = containers.flatMap(c => c.changed);
784
- const names = [...new Set(changed.map(x => x.was || x.now))];
785
- const moves = [...new Set([...movedKeys].filter(k => k && k[0] === '@').map(label))];
786
- const what = [moves.length && `moved ${moves.join(', ')}`, copies.length && `copied ${copies.map(c => `${c.of} ("${String(c.text).slice(0, 40)}")`).join(', ')}`].filter(Boolean).join('; ');
927
+ // A key without text reads as its tag ("IMG:#2" as "<img> #2")
928
+ const readable = (l) => String(l).replace(/^([A-Za-z][\w-]*):(#\d+)?$/, (all, t, n) => `<${t.toLowerCase()}>${n ? ' ' + n : ''}`);
929
+ const names = [...new Set(changed.map(x => readable(x.was || x.now)))];
930
+ const moves = [...new Set([...movedKeys].filter(k => k && k[0] === '@' && !deleted.has(k)).map(k => readable(label(k))))];
931
+ const dels = [...new Set([...deleted].map(k => readable(label(k))))];
932
+ const what = [dels.length && `deleted ${dels.join(', ')}`, moves.length && `moved ${moves.join(', ')}`, copies.length && `copied ${copies.map(c => `${readable(c.of)} ("${String(c.text).slice(0, 40)}")`).join(', ')}`].filter(Boolean).join('; ');
787
933
  found.push({ region, key: '', element: containers.map(c => c.container ? label(c.container) : region).join(', '), prop: 'structure',
788
934
  value: { changed, moved: moves, copies }, before: null,
789
- reason: `${names.join(', ')} changed in the source where the layout was edited, so the layout edits (${what || 'reordering'}) were not applied` });
935
+ reason: containers.some(c => c.copy) && changed.every(x => x.was === x.now)
936
+ ? `the copied element ${names.join(', ')} has identical twins that were reordered or replaced in the source, so the layout edits (${what || 'reordering'}) were not applied`
937
+ : changed.every(x => x.was === x.now)
938
+ ? `identical elements ${names.join(', ')} were reordered or replaced in the source where the layout was edited, so the layout edits (${what || 'reordering'}) were not applied`
939
+ : `${names.join(', ')} changed in the source where the layout was edited, so the layout edits (${what || 'reordering'}) were not applied` });
790
940
  });
791
941
  found.forEach(f => { conflicts.push(f); if (persistOf(f.region)) keptConflicts.add(f); });
792
942
  let c = 0;
793
943
  log = log.filter((d, i) => { const keep = !gone(d); if (keep && i < cursor) c++; return keep; });
794
944
  cursor = c; ver++;
945
+ refreshIds();
795
946
  saveState(); refresh();
796
947
  if (found.length) {
797
948
  if (estore) estore.conflicts = conflicts.slice();
@@ -880,7 +1031,7 @@
880
1031
  ver++; saveState(); refresh();
881
1032
  return true;
882
1033
  }
883
- const d = pushDelta(Object.assign({ kind: 'st-node', region, path, prop, value, before, sig: nodeSig(el) }, opts.join ? { join: true } : {}));
1034
+ const d = pushDelta(Object.assign({ kind: 'st-node', region, path, prop, value, before, sig: nodeSig(el) }, twinKey(path) ? (() => { const t = withIds({}, [path]); if (t.ids && t.ids[path]) t.id = t.ids[path]; return t; })() : {}, opts.join ? { join: true } : {}));
884
1035
  if (opts.coalesce) stamps.set(d, Date.now());
885
1036
  return true;
886
1037
  }
@@ -927,7 +1078,8 @@
927
1078
  function commitOrder(area, container, before) {
928
1079
  const order = staticKeys(container);
929
1080
  if (eq(before, order)) return false;
930
- pushDelta({ kind: 'st-order', region: key(area), parent: parentKey(container, area), order, before });
1081
+ const d = { kind: 'st-order', region: key(area), parent: parentKey(container, area), order, before };
1082
+ pushDelta(withIds(d, before));
931
1083
  return true;
932
1084
  }
933
1085
  // A piece that already sits in its new container. Identity never changes, so one
@@ -936,6 +1088,7 @@
936
1088
  const toContainer = item.parentElement;
937
1089
  const d = { kind: 'st-move', from: key(fromArea), to: key(toArea), fromParent: parentKey(fromContainer, fromArea), toParent: parentKey(toContainer, toArea), key: idOf(item), fromOrder: staticKeys(fromContainer), toOrder: staticKeys(toContainer), fromBefore, toBefore };
938
1090
  if (opts.join) d.join = true;
1091
+ withIds(d, [originOf(d.key), ...fromBefore, ...toBefore]);
939
1092
  pushDelta(d);
940
1093
  resetAreas();
941
1094
  markStatic(toArea);
@@ -2687,14 +2840,23 @@
2687
2840
  // so the server can refuse when a file changed underneath this page.
2688
2841
  // With them, each source element's fingerprint as loaded: the server refuses an edit
2689
2842
  // whose element no longer matches (changed, or a twin that moved).
2690
- let baseFiles = null, baseIds = null;
2843
+ let baseFiles = null, baseIds = null, baseCids = null, basePending = null;
2844
+ const cidsUnsure = new Set();
2845
+ // A source element's content id as the base read it (its whole source slice, hashed)
2846
+ const cidOf = (k) => {
2847
+ const o = originOf(k); if (typeof o !== 'string' || o[0] !== '@') return null;
2848
+ const a = areaByKey(decodeURIComponent(o.slice(1, o.indexOf('@', 1)))), m = baseCids && a && baseCids[sourceFile(a)];
2849
+ return m && m[o] || null;
2850
+ };
2691
2851
  function loadBase(filesOnly) {
2692
2852
  if (!/^https?:$/.test(location.protocol) || typeof fetch !== 'function') return Promise.resolve(null);
2693
- return fetch('/__edit/base', { cache: 'no-store' }).then(r => r.ok ? r.json() : null).then(j => {
2853
+ const p = fetch('/__edit/base', { cache: 'no-store' }).then(r => r.ok ? r.json() : null).then(j => {
2694
2854
  if (j && j.files) baseFiles = j.files;
2695
- if (j && j.ids && !filesOnly) baseIds = j.ids;
2855
+ if (j && j.ids && !filesOnly) { baseIds = j.ids; baseCids = j.cids || null; }
2696
2856
  return baseFiles;
2697
2857
  }).catch(() => null);
2858
+ if (!filesOnly) basePending = p;
2859
+ return p;
2698
2860
  }
2699
2861
  // Stylesheets and data hot-swap: their new hash applies. HTML waits for the reload
2700
2862
  // (a cancelled one leaves the page on what it loaded); our own writes advance on publish.
@@ -2803,17 +2965,62 @@
2803
2965
  // its HTML hashes are not taken (a plain publish is stale until a reload), nor the
2804
2966
  // fingerprints of keys with twins there (which may not be the elements this page shows).
2805
2967
  let overNewer = false;
2968
+ // Each page element's content id as this page holds it (its loaded one; a copy its source's),
2969
+ // or null where an edit in it changed its content
2970
+ // (unknown, too, where a structural edit was made inside it, or for a copy whose source was
2971
+ // edited before it was copied)
2972
+ function shownCids() {
2973
+ const done = log.slice(0, cursor), live = keyMap(staticAreas()), out = new Map();
2974
+ const edited = new Set(done.filter(d => d.kind === 'st-node').map(d => d.path));
2975
+ const parents = new Set();
2976
+ done.forEach(d => { if (d.kind === 'st-children' || d.kind === 'st-order') parents.add(d.parent); if (d.kind === 'st-move') { parents.add(d.fromParent); parents.add(d.toParent); } });
2977
+ const changedIn = (el) => !!el && ([el, ...el.querySelectorAll('[data-edit-key]')].some(n => edited.has(n.getAttribute('data-edit-key')))
2978
+ || [...parents].some(p => { if (!p) return false; const c = live.get(p); return !!c && (c === el || el.contains(c)); }));
2979
+ live.forEach((el, k) => {
2980
+ if (k[0] === '!' || changedIn(el)) return out.set(el, null);
2981
+ if (k[0] === '~') { const o = originOf(k); if (edited.has(o) || [...edited].some(e => { const n = live.get(e), src = live.get(o); return n && src && src.contains(n); }) || changedIn(live.get(o))) return out.set(el, null); }
2982
+ out.set(el, cidOf(originOf(k)));
2983
+ });
2984
+ return out;
2985
+ }
2986
+ // Over a newer file: a twin family the written file holds in another order than the page shows
2987
+ // (after this publish's own edits, re-keyed as a fresh load) is unverifiable until a reload.
2988
+ // Families with no evidence of a reorder (own edits, changes in place) keep their identity.
2989
+ function compareWritten(written, shown) {
2990
+ const live = keyMap(staticAreas());
2991
+ Object.entries(written).forEach(([f, now]) => {
2992
+ if (!/\.html?$/i.test(f)) return;
2993
+ now = now || {};
2994
+ const kept = {};
2995
+ new Set(Object.keys(now).map(familyOf)).forEach(fam => {
2996
+ const ks = Object.keys(now).filter(k => familyOf(k) === fam).sort(byOrd);
2997
+ const pk = [...live.keys()].filter(k => familyOf(k) === fam && (() => { const a = regionOf(live.get(k)); return a && sourceFile(a) === f; })()).sort(byOrd);
2998
+ const R = pk.map(k => shown.has(live.get(k)) ? shown.get(live.get(k)) : null), F = ks.map(k => now[k]);
2999
+ if (!R.includes(null) && R.some((x, i) => (movedIn(R, F, i) || []).length)) cidsUnsure.add(fam);
3000
+ else ks.forEach(k => { kept[k] = now[k]; });
3001
+ });
3002
+ baseCids[f] = kept;
3003
+ });
3004
+ }
2806
3005
  function publishNow(opts) {
2807
3006
  const done = (r, keep, heldRes) => {
2808
3007
  if (r && r.base && baseFiles) Object.entries(r.base).forEach(([f, h]) => { if (!overNewer || !/\.html?$/i.test(f)) baseFiles[f] = h; });
2809
3008
  if (r && r.ids && baseIds) {
2810
3009
  if (!overNewer) baseIds = r.ids;
2811
3010
  else Object.entries(r.ids).forEach(([f, m]) => { baseIds[f] = Object.assign({}, baseIds[f]); Object.entries(m || {}).forEach(([k, fp]) => { if (!String(fp).includes('.')) baseIds[f][k] = fp; }); });
3011
+ // Content ids of the file as written: edits from here keep their twins' identity. Over a
3012
+ // newer file the page shows less than it: its twins are unverifiable until a reload.
3013
+ if (!overNewer) { baseCids = r.cids || null; cidsUnsure.clear(); }
2812
3014
  }
3015
+ const overCids = overNewer && r && r.cids && baseCids ? r.cids : null;
3016
+ const shown = overCids ? shownCids() : null;
2813
3017
  const stale = r && Array.isArray(r.stale) ? r.stale : [];
2814
3018
  if (estore) estore.stale = stale;
2815
3019
  if (stale.length) document.dispatchEvent(new CustomEvent('edit:stale', { detail: { files: stale } }));
2816
- if (published(keep ? { results: r.results.filter(x => !(x && (keep.has(x.region) || (heldRes && heldRes.has(x))))) } : r)) rebase(keep);
3020
+ if (published(keep ? { results: r.results.filter(x => !(x && (keep.has(x.region) || (heldRes && heldRes.has(x))))) } : r)) {
3021
+ rebase(keep);
3022
+ if (overCids) compareWritten(overCids, shown);
3023
+ }
2817
3024
  takeHeldReload();
2818
3025
  return r;
2819
3026
  };
@@ -2951,8 +3158,11 @@
2951
3158
  log = kept; cursor = c; ver++;
2952
3159
  saveState();
2953
3160
  }
3161
+ const BASE_WAIT = 4000; // then replay positionally, as without a base
2954
3162
  function restore() {
2955
3163
  if (!log.length) return;
3164
+ // Twin identities are checked against the base: wait for it once
3165
+ if (!baseCids && basePending && log.some(d => d.ids || d.id)) { const p = basePending; basePending = null; Promise.race([p, new Promise(r => setTimeout(r, BASE_WAIT))]).then(restore, restore); return; }
2956
3166
  pruneLoaded();
2957
3167
  for (const [k, v] of Object.entries(fold())) { const area = areaByKey(k); if (area && v.kind === 'data') waitForData(area, () => applySnap(area, 'data', v.snap)); }
2958
3168
  if (log.some(d => /^st-/.test(d.kind))) { surfaceConflicts(areas()); applyStaticState(); }
@@ -3012,7 +3222,13 @@
3012
3222
  if (window.__manifestEditStub) setTimeout(() => { window.__manifestEditStub.v++; }, 0);
3013
3223
  loadState();
3014
3224
  if (window.__mnfstEdit) loadBase(); // only mnfst-run --edit serves the base
3015
- setTimeout(() => { armAll(); restore(); }, 450);
3225
+ // A log with twin ids waits (bounded) for the base before the page arms: nothing is editable
3226
+ // while the source shows without its pending edits
3227
+ setTimeout(() => {
3228
+ const go = () => { armAll(); restore(); };
3229
+ if (!baseCids && basePending && log.some(d => d.ids || d.id)) { const p = basePending; basePending = null; Promise.race([p, new Promise(r => setTimeout(r, BASE_WAIT))]).then(go, go); }
3230
+ else go();
3231
+ }, 450);
3016
3232
  document.addEventListener('keydown', onHistoryKey);
3017
3233
  window.addEventListener('click', onAreaLinkClick, true);
3018
3234
  window.addEventListener('auxclick', onAreaLinkClick, true);