| 1 | import type { EntryChange, EntryOptions } from '@deepseek-ai/cordis-plugin-loader' |
| 2 | import { deepEqual, type Dict, omit } from '@deepseek-ai/cosmokit' |
| 3 | |
| 4 | /** One tree-side mutation that has not reached the file yet, keyed by entry id. */ |
| 5 | export type JournalRecord = JournalRecord.Remove | JournalRecord.Upsert |
| 6 | |
| 7 | export namespace JournalRecord { |
| 8 | export interface Remove { |
| 9 | kind: 'remove' |
| 10 | } |
| 11 | |
| 12 | export interface Upsert { |
| 13 | kind: 'upsert' |
| 14 | /** The entry did not exist when the tree first reported it. */ |
| 15 | created: boolean |
| 16 | /** |
| 17 | * The group the tree placed the entry in (`null` for the root), or |
| 18 | * `undefined` when the tree did not relocate it. |
| 19 | */ |
| 20 | parent: string | null | undefined |
| 21 | /** Index within `parent`; only meaningful alongside a `parent`. */ |
| 22 | position: number |
| 23 | /** |
| 24 | * Per-key delta relative to the options the entry had when the change |
| 25 | * was reported; `undefined` deletes a key. Collected at report time: the |
| 26 | * live tree is reconciled asynchronously and may lag behind the file. |
| 27 | */ |
| 28 | changes: Dict |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | export type Journal = Map<string, JournalRecord> |
| 33 | |
| 34 | export function diffOptions(legacy: EntryOptions, options: EntryOptions) { |
| 35 | const changes: Dict = {} |
| 36 | for (const key of new Set([...Object.keys(legacy), ...Object.keys(options)])) { |
| 37 | if (key === 'id') continue |
| 38 | if (deepEqual((legacy as unknown as Record<string, unknown>)[key], (options as unknown as Record<string, unknown>)[key])) continue |
| 39 | changes[key] = (options as unknown as Record<string, unknown>)[key] |
| 40 | } |
| 41 | return changes |
| 42 | } |
| 43 | |
| 44 | /** Fold a later record into an earlier one for the same entry. */ |
| 45 | export function mergeRecords(older: JournalRecord | undefined, newer: JournalRecord): JournalRecord | undefined { |
| 46 | if (!older) return newer |
| 47 | if (newer.kind === 'remove') { |
| 48 | // an entry created and removed before ever being written leaves no trace |
| 49 | return older.kind === 'upsert' && older.created ? undefined : newer |
| 50 | } |
| 51 | if (older.kind === 'remove') { |
| 52 | return { ...newer, created: false } |
| 53 | } |
| 54 | const relocated = newer.parent !== undefined |
| 55 | return { |
| 56 | kind: 'upsert', |
| 57 | created: older.created, |
| 58 | parent: relocated ? newer.parent : older.parent, |
| 59 | position: relocated ? newer.position : older.position, |
| 60 | changes: { ...older.changes, ...newer.changes }, |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | export function merge(journal: Journal, id: string, record: JournalRecord) { |
| 65 | const merged = mergeRecords(journal.get(id), record) |
| 66 | if (merged) { |
| 67 | journal.set(id, merged) |
| 68 | } else { |
| 69 | journal.delete(id) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | export function record(journal: Journal, change: EntryChange, parent: string | null) { |
| 74 | const { id, options, legacy } = change |
| 75 | if (!options) { |
| 76 | return merge(journal, id, { kind: 'remove' }) |
| 77 | } |
| 78 | const position = change.group.data.indexOf(options) |
| 79 | if (!legacy) { |
| 80 | return merge(journal, id, { kind: 'upsert', created: true, parent, position, changes: omit(options, ['id']) }) |
| 81 | } |
| 82 | merge(journal, id, { |
| 83 | kind: 'upsert', |
| 84 | created: false, |
| 85 | parent: change.from ? parent : undefined, |
| 86 | position, |
| 87 | changes: diffOptions(legacy, options), |
| 88 | }) |
| 89 | } |
| 90 | |
| 91 | export interface FlatEntry { |
| 92 | parent: string | null |
| 93 | position: number |
| 94 | options: EntryOptions |
| 95 | list: EntryOptions[] |
| 96 | } |
| 97 | |
| 98 | /** Index every entry (including nested group members) by id. */ |
| 99 | export function flatten(data: EntryOptions[], parent: string | null = null, result = new Map<string, FlatEntry>()) { |
| 100 | data.forEach((options, position) => { |
| 101 | if (options.id) result.set(options.id, { parent, position, options, list: data }) |
| 102 | if (options.group && Array.isArray(options.config)) { |
| 103 | flatten(options.config, options.id ?? null, result) |
| 104 | } |
| 105 | }) |
| 106 | return result |
| 107 | } |
| 108 | |
| 109 | export function applyChanges(options: EntryOptions, changes: Dict, filter?: (key: string) => boolean) { |
| 110 | for (const [key, value] of Object.entries(changes)) { |
| 111 | if (filter && !filter(key)) continue |
| 112 | if (value === undefined) { |
| 113 | delete (options as unknown as Record<string, unknown>)[key] |
| 114 | } else { |
| 115 | (options as unknown as Record<string, unknown>)[key] = value |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | export function detach(data: EntryOptions[], id: string) { |
| 121 | const flat = flatten(data).get(id) |
| 122 | if (!flat) return |
| 123 | flat.list.splice(flat.list.indexOf(flat.options), 1) |
| 124 | return flat.options |
| 125 | } |
| 126 | |
| 127 | /** |
| 128 | * Insert `options` under `parent` (a group id, or `null` for the root) at |
| 129 | * `position`, clamped to the group's length. Returns false when the parent |
| 130 | * group does not exist. |
| 131 | */ |
| 132 | export function place(data: EntryOptions[], options: EntryOptions, parent: string | null, position: number) { |
| 133 | let list = data |
| 134 | if (parent !== null) { |
| 135 | const group = flatten(data).get(parent) |
| 136 | if (!group?.options.group) return false |
| 137 | list = group.options.config ??= [] |
| 138 | } |
| 139 | list.splice(Math.min(position, list.length), 0, options) |
| 140 | return true |
| 141 | } |
| 142 | |
| 143 | /** |
| 144 | * Overlay a journal onto `data` in place. `filter(id, key)` restricts which |
| 145 | * changes apply; `key` is `null` when asking about the entry as a whole |
| 146 | * (creation, removal, relocation). |
| 147 | */ |
| 148 | export function applyJournal( |
| 149 | data: EntryOptions[], |
| 150 | journal: Journal, |
| 151 | filter: (id: string, key: string | null) => boolean = () => true, |
| 152 | warn: (format: string, ...args: any[]) => void = () => {}, |
| 153 | ) { |
| 154 | for (const [id, record] of journal) { |
| 155 | if (!filter(id, null)) continue |
| 156 | if (record.kind === 'remove') { |
| 157 | detach(data, id) |
| 158 | continue |
| 159 | } |
| 160 | const flat = flatten(data).get(id) |
| 161 | if (!flat) { |
| 162 | const options = { id } as EntryOptions |
| 163 | applyChanges(options, record.changes, key => filter(id, key)) |
| 164 | const parent = record.parent ?? null |
| 165 | if (!place(data, options, parent, record.position)) { |
| 166 | warn('cannot place entry %C: group %C not found', id, parent) |
| 167 | } |
| 168 | continue |
| 169 | } |
| 170 | applyChanges(flat.options, record.changes, key => filter(id, key)) |
| 171 | if (record.parent !== undefined && flat.parent !== record.parent) { |
| 172 | detach(data, id) |
| 173 | if (!place(data, flat.options, record.parent, record.position)) { |
| 174 | warn('cannot move entry %C: group %C not found', id, record.parent) |
| 175 | place(data, flat.options, flat.parent, flat.position) |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | return data |
| 180 | } |
| 181 | |
| 182 | export interface Conflict { |
| 183 | id: string |
| 184 | reason: string |
| 185 | } |
| 186 | |
| 187 | /** |
| 188 | * Three-way reconciliation of a journal against a new file state. The file |
| 189 | * wins every conflict: conflicting keys are dropped from the journal so that |
| 190 | * the tree follows the file, and each drop is reported. |
| 191 | * |
| 192 | * `fileOwned(id, key)` scopes the check to what the file can actually express |
| 193 | * (patch-owned keys and patch-inserted entries live elsewhere). |
| 194 | */ |
| 195 | export function reconcile( |
| 196 | journal: Journal, |
| 197 | base: Map<string, FlatEntry>, |
| 198 | theirs: Map<string, FlatEntry>, |
| 199 | fileOwned: (id: string, key: string | null) => boolean, |
| 200 | ) { |
| 201 | const conflicts: Conflict[] = [] |
| 202 | for (const [id, record] of journal) { |
| 203 | if (!fileOwned(id, null)) continue |
| 204 | const b = base.get(id) |
| 205 | const t = theirs.get(id) |
| 206 | if (record.kind === 'remove') { |
| 207 | if (!t) { |
| 208 | journal.delete(id) |
| 209 | } else if (!b || !deepEqual(t.options, b.options)) { |
| 210 | conflicts.push({ id, reason: b ? 'modified in file, removed at runtime' : 'added in file, removed at runtime' }) |
| 211 | journal.delete(id) |
| 212 | } |
| 213 | continue |
| 214 | } |
| 215 | if (!t) { |
| 216 | if (b) { |
| 217 | conflicts.push({ id, reason: 'removed in file, modified at runtime' }) |
| 218 | journal.delete(id) |
| 219 | } |
| 220 | // else: created at runtime, nothing in the file to conflict with |
| 221 | continue |
| 222 | } |
| 223 | if (record.created) record.created = false |
| 224 | for (const key of Object.keys(record.changes)) { |
| 225 | if (!fileOwned(id, key)) continue |
| 226 | const bv = (b?.options as unknown as Record<string, unknown> | undefined)?.[key] |
| 227 | const tv = (t.options as unknown as Record<string, unknown>)[key] |
| 228 | if (deepEqual(bv, tv) || deepEqual(tv, record.changes[key])) continue |
| 229 | conflicts.push({ id, reason: `key "${key}" modified both in file and at runtime` }) |
| 230 | delete record.changes[key] |
| 231 | } |
| 232 | if (record.parent !== undefined && b && t.parent !== b.parent && t.parent !== record.parent) { |
| 233 | conflicts.push({ id, reason: 'moved both in file and at runtime' }) |
| 234 | record.parent = undefined |
| 235 | } |
| 236 | const moved = record.parent !== undefined && record.parent !== t.parent |
| 237 | if (!Object.keys(record.changes).length && !moved) { |
| 238 | journal.delete(id) |
| 239 | } |
| 240 | } |
| 241 | return conflicts |
| 242 | } |
| 243 |