mnfst 0.5.320 → 0.5.322

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