Files
faunosteo/packages/anatomy/src/curation/migration-map.ts
T

179 lines
5.7 KiB
TypeScript

import type { ReportMigrationMap, SheetRef } from '@faunosteo/domain'
import type { LegacyIdMap } from '../legacy/types'
import { allFindings, topCollection, type Item } from './targets'
import type { ChangeRecord } from './types'
/**
* Report migration map: where every identifier a Report v2 may carry lands
* in the curated draft. Annotations come from the legacy id map (then
* follow annotation renames), finding paths from replaying the applier's
* rename, move and remove records over every node of the legacy baseline.
* A node removed with its category and re-added under another category at
* the same relative place (the sphenoid restructure) is re-homed when the
* match is unique; anything else stays null = "removed", and the report
* keeps the finding with its snapshots.
*/
const FINDING = 'finding:'
export interface MigrationMapInput {
baseline: Item
final: Item
legacyIdMap: LegacyIdMap
records: readonly ChangeRecord[]
sheet: SheetRef
mainViewId: string
}
export interface MigrationMapStats {
nodes: number
identical: number
remapped: number
rehomed: number
removed: number
}
interface PathEntry {
legacy: string
current: string | null
rehomed: boolean
}
function strip(target: string): string {
return target.slice(FINDING.length)
}
function lastSegment(path: string): string {
return path.slice(path.lastIndexOf('/') + 1)
}
function withLastSegment(path: string, id: string): string {
const cut = path.lastIndexOf('/')
return cut < 0 ? id : `${path.slice(0, cut + 1)}${id}`
}
function replacePrefix(entries: PathEntry[], from: string, to: string | null) {
for (const entry of entries) {
const current = entry.current
if (current === null) continue
if (current === from) entry.current = to
else if (current.startsWith(`${from}/`)) {
entry.current = to === null ? null : `${to}${current.slice(from.length)}`
}
}
}
function applyRecord(
entries: PathEntry[],
ids: { annotations: Map<string, string>; views: Map<string, string> },
record: ChangeRecord,
) {
const { op, target } = record
if (op.op !== 'rename' && op.op !== 'remove' && op.op !== 'move') return
if (target.startsWith(FINDING)) {
const from = strip(target)
if (op.op === 'rename')
replacePrefix(entries, from, withLastSegment(from, op.id))
if (op.op === 'remove') replacePrefix(entries, from, null)
if (op.op === 'move')
replacePrefix(entries, from, `${strip(op.to)}/${lastSegment(from)}`)
return
}
const [kind, id] = target.split(':', 2) as [string, string]
if (kind === 'zone') {
for (const entry of entries) {
if (entry.current?.startsWith(`${id}/`)) {
entry.current =
op.op === 'remove'
? null
: `${op.op === 'rename' ? op.id : id}${entry.current.slice(id.length)}`
}
}
return
}
if (op.op === 'rename' && (kind === 'annotation' || kind === 'view')) {
const map = kind === 'annotation' ? ids.annotations : ids.views
for (const [legacy, current] of map)
if (current === id) map.set(legacy, op.id)
}
}
/** `zone/<any category>/<rest>` present exactly once in the final document. */
function rehome(entry: PathEntry, finalPaths: ReadonlySet<string>): void {
const [zone, , ...rest] = entry.legacy.split('/')
if (rest.length === 0) return
const tail = `/${rest.join('/')}`
const matches = [...finalPaths].filter(
(p) =>
p.startsWith(`${zone}/`) &&
p.endsWith(tail) &&
p.split('/').length === rest.length + 2,
)
if (matches.length === 1) {
entry.current = matches[0]!
entry.rehomed = true
}
}
function annotationNames(doc: Item): Map<string, { fr: string; en: string }> {
const names = new Map<string, { fr: string; en: string }>()
for (const a of topCollection(doc, 'annotation')) {
const name = a.name as { fr?: string; en?: string } | null
names.set(String(a.id), { fr: name?.fr ?? '', en: name?.en ?? '' })
}
return names
}
export function buildReportMigrationMap(input: MigrationMapInput): {
map: ReportMigrationMap
stats: MigrationMapStats
} {
const entries: PathEntry[] = allFindings(input.baseline).map((e) => ({
legacy: strip(e.target),
current: strip(e.target),
rehomed: false,
}))
const ids = {
annotations: new Map(Object.entries(input.legacyIdMap.annotations)),
views: new Map(Object.entries(input.legacyIdMap.views)),
}
for (const record of input.records) applyRecord(entries, ids, record)
const finalPaths = new Set(
allFindings(input.final).map((e) => strip(e.target)),
)
for (const entry of entries) {
if (entry.current !== null && !finalPaths.has(entry.current))
entry.current = null
if (entry.current === null) rehome(entry, finalPaths)
}
const legacyNames = annotationNames(input.baseline)
const importIds = new Map(Object.entries(input.legacyIdMap.annotations))
const annotations: ReportMigrationMap['annotations'] = {}
for (const [legacy, finalId] of ids.annotations) {
annotations[legacy] = {
id: finalId,
name: legacyNames.get(importIds.get(legacy)!) ?? { fr: '', en: '' },
}
}
const finding_paths: Record<string, string | null> = {}
for (const entry of entries) finding_paths[entry.legacy] = entry.current
const map: ReportMigrationMap = {
schema_version: 1,
sheet: input.sheet,
main_view_id: input.mainViewId,
views: Object.fromEntries(ids.views),
annotations,
finding_paths,
}
const stats: MigrationMapStats = {
nodes: entries.length,
identical: entries.filter((e) => e.current === e.legacy).length,
remapped: entries.filter(
(e) => e.current !== null && e.current !== e.legacy && !e.rehomed,
).length,
rehomed: entries.filter((e) => e.rehomed).length,
removed: entries.filter((e) => e.current === null).length,
}
return { map, stats }
}