import type { Change, Document, ElementRecord, Id, Registry } from './types.ts'; import { applyChanges, validateDocument } from './document.ts'; import { freeze } from './values.ts'; /** Pure history execution, also used to validate recovery proposals before publication. */ export function planHistoryChanges(initial:Document,planned:readonly Change[],registry:Registry){ const generations=new Map>(); const incarnation=(id:Id,value:number)=>{const mapping=generations.get(id);while(mapping?.has(value))value=mapping.get(value)!;return value;}; const remap=(change:Change):Change=>{ if(change.kind==='field'){const next=incarnation(change.target.id,change.target.incarnation);return next===change.target.incarnation?change:freeze({...change,target:{...change.target,incarnation:next}});} if(change.kind==='element'){const record=(value:ElementRecord|null)=>value?{...value,incarnation:incarnation(value.id,value.incarnation)}:null;return freeze({...change,before:record(change.before),after:record(change.after)});} return change; }; let document=initial;const changes:Change[]=[]; for(const original of planned){ let change=remap(original); if(change.kind==='element'&&!change.before&&change.after){const dead=document.tombstones.get(change.id);if(dead!==undefined&&change.after.incarnation<=dead){const mapping=generations.get(change.id)??new Map();mapping.set(change.after.incarnation,dead+1);generations.set(change.id,mapping);change=remap(change);}} document=applyChanges(document,[change]);changes.push(change); } validateDocument(document,registry); return{document,changes:freeze(changes),remap,restored:generations.size>0}; }