Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Sources/ConvertCore/FormatRegistry.swift2// Description: The registry of real conversion capabilities, built from the engines. It indexes declared paths,3// excludes (and reports) the paths of engines whose bundled components are missing, and exports the4// compatibility matrix as Markdown and JSON.5// Author: Simon-Pierre Boucher — contact@spboucher.ai6import Foundation78/// An engine whose bundled component is missing: its paths are not offered.9public struct UnavailableEngine: Sendable, Hashable, Codable, Identifiable {10 public let id: String11 public let displayName: String12 public let reason: String13 /// The paths the engine would offer if its component were present.14 public let paths: [ConversionPath]15}1617/// One row of the compatibility matrix.18public struct MatrixRow: Sendable, Hashable, Codable {19 public let source: FormatID20 public let destination: FormatID21 public let operation: String?22 public let engine: String23 /// `supported`, `experimental` or `unavailable` (engine component missing in this build).24 public let status: String25 public let fidelity: Fidelity26 /// Sorted raw values of the preserved aspects.27 public let preserves: [String]28 public let limitations: [String]29 /// Reason an `unavailable` row is unavailable.30 public let unavailableReason: String?31}3233/// Totals describing what the registry really offers.34public struct RegistryCounts: Sendable, Hashable, Codable {35 /// Formats appearing as source or destination of at least one available path.36 public let formatsWithPath: Int37 public let sourceFormats: Int38 public let destinationFormats: Int39 /// Distinct (source, destination) pairs with at least one available path, operations included.40 public let distinctPairs: Int41 /// Distinct (source, destination) pairs with at least one available path of status `supported`.42 public let verifiedPairs: Int43 /// Distinct plain conversions (no named operation).44 public let conversionPairs: Int45 /// Distinct named operations (`pdf.merge`, `archive.extract`…).46 public let operations: Int47 public let availablePaths: Int48 public let unavailablePaths: Int49 public let engines: Int50 public let unavailableEngines: Int51}5253/// Immutable index of what the engines can do. Engine availability is evaluated once, when the registry is built;54/// build a new registry after installing components.55public struct FormatRegistry: Sendable {56 /// Every engine handed to the registry (first one wins when two share an identifier).57 public let engines: [any ConversionEngine]58 /// Paths of available engines, in a stable order (source, destination, operation, engine).59 public let paths: [ConversionPath]60 /// Engines excluded because a component is missing, with the reason.61 public let unavailableEngines: [UnavailableEngine]62 /// Problems found while indexing (duplicate engine identifiers, paths naming another engine, duplicate paths).63 public let diagnostics: [String]6465 private let enginesByID: [String: any ConversionEngine]66 private let bySource: [FormatID: [ConversionPath]]67 private let byDestination: [FormatID: [ConversionPath]]68 private let inspectors: [FormatID: [String]]6970 public init(engines list: [any ConversionEngine]) {71 var unique: [any ConversionEngine] = []72 var byID: [String: any ConversionEngine] = [:]73 var notes: [String] = []74 for engine in list {75 if byID[engine.id] != nil {76 notes.append("Engine identifier '\(engine.id)' is declared twice; the second engine is ignored.")77 continue78 }79 byID[engine.id] = engine80 unique.append(engine)81 }82 var available: [ConversionPath] = []83 var unavailable: [UnavailableEngine] = []84 var inspectors: [FormatID: [String]] = [:]85 var seen = Set<String>()86 for engine in unique {87 var own: [ConversionPath] = []88 for path in engine.paths {89 if path.engine != engine.id {90 notes.append("Path \(path.id) is declared by engine '\(engine.id)' but names engine '\(path.engine)'; ignored.")91 } else if !seen.insert(path.id).inserted {92 notes.append("Path \(path.id) is declared twice; the duplicate is ignored.")93 } else {94 own.append(path)95 }96 }97 switch engine.availability() {98 case .available:99 available.append(contentsOf: own)100 for format in engine.inspectableFormats { inspectors[format, default: []].append(engine.id) }101 case .unavailable(let reason):102 unavailable.append(UnavailableEngine(id: engine.id, displayName: engine.displayName, reason: reason, paths: own))103 }104 }105 available.sort(by: Self.pathOrder)106 engines = unique107 enginesByID = byID108 paths = available109 unavailableEngines = unavailable110 diagnostics = notes111 bySource = Dictionary(grouping: available, by: \.source)112 byDestination = Dictionary(grouping: available, by: \.destination)113 self.inspectors = inspectors114 }115116 private static func pathOrder(_ a: ConversionPath, _ b: ConversionPath) -> Bool {117 (a.source.rawValue, a.destination.rawValue, a.operation ?? "", a.engine) < (b.source.rawValue, b.destination.rawValue, b.operation ?? "", b.engine)118 }119120 // MARK: Engines121122 public func engine(id: String) -> (any ConversionEngine)? { enginesByID[id] }123124 /// Availability of an engine as evaluated when the registry was built (`nil` for an unknown identifier).125 public func availability(ofEngine id: String) -> EngineAvailability? {126 if let missing = unavailableEngines.first(where: { $0.id == id }) { return .unavailable(reason: missing.reason) }127 return enginesByID[id] == nil ? nil : .available128 }129130 /// The available engine that inspects `format`, if any. Among the engines that list the format as inspectable,131 /// the one that treats it as its own kind of file wins, whatever the registration order:132 ///133 /// 1. an engine with a plain conversion from the format to a destination of the **same category** (the image134 /// engine for PNG, not a PDF engine that merely accepts images to build a PDF);135 /// 2. otherwise an engine with any path from the format to a same-category destination;136 /// 3. otherwise the first registered.137 public func inspector(for format: FormatID) -> (any ConversionEngine)? {138 guard let candidates = inspectors[format], !candidates.isEmpty else { return nil }139 let category = FormatCatalog.format(format)?.category140 func rank(_ id: String) -> Int {141 let own = (bySource[format] ?? []).filter { $0.engine == id && FormatCatalog.format($0.destination)?.category == category }142 if own.contains(where: { $0.operation == nil }) { return 0 }143 return own.isEmpty ? 2 : 1144 }145 let best = candidates.enumerated().min { (rank($0.element), $0.offset) < (rank($1.element), $1.offset) }146 return best.flatMap { enginesByID[$0.element] }147 }148149 // MARK: Paths150151 /// Available paths matching the given criteria. `operation: .some(nil)` selects plain conversions,152 /// `.some("pdf.merge")` a named operation, and omitting it selects both.153 public func paths(from source: FormatID? = nil, to destination: FormatID? = nil, operation: String?? = nil, engine: String? = nil) -> [ConversionPath] {154 let base: [ConversionPath]155 if let source { base = bySource[source] ?? [] } else if let destination { base = byDestination[destination] ?? [] } else { base = paths }156 return base.filter { path in157 (source == nil || path.source == source) && (destination == nil || path.destination == destination)158 && (engine == nil || path.engine == engine) && (operation.map { $0 == path.operation } ?? true)159 }160 }161162 /// Formats that at least one available path can read, sorted.163 public var sourceFormats: [FormatID] { bySource.keys.sorted() }164165 /// Formats that at least one available path can write, sorted.166 public var destinationFormats: [FormatID] { byDestination.keys.sorted() }167168 /// Destinations reachable from `source` by a plain conversion (and by named operations when asked), sorted.169 public func destinations(for source: FormatID, includingOperations: Bool = false) -> [FormatID] {170 Set((bySource[source] ?? []).filter { includingOperations || $0.operation == nil }.map(\.destination)).sorted()171 }172173 /// Named operations available for `source`.174 public func operations(for source: FormatID) -> [ConversionPath] { (bySource[source] ?? []).filter { $0.operation != nil } }175176 /// Paths that exist in this build's engines but cannot run because a component is missing.177 public func unavailablePaths(from source: FormatID? = nil, to destination: FormatID? = nil) -> [(path: ConversionPath, reason: String)] {178 unavailableEngines.flatMap { engine in179 engine.paths.filter { (source == nil || $0.source == source) && (destination == nil || $0.destination == destination) }180 .map { (path: $0, reason: engine.reason) }181 }182 }183184 public var counts: RegistryCounts {185 func pair(_ p: ConversionPath) -> String { p.source.rawValue + ">" + p.destination.rawValue }186 return RegistryCounts(187 formatsWithPath: Set(bySource.keys).union(byDestination.keys).count,188 sourceFormats: bySource.count,189 destinationFormats: byDestination.count,190 distinctPairs: Set(paths.map(pair)).count,191 verifiedPairs: Set(paths.filter { $0.status == .supported }.map(pair)).count,192 conversionPairs: Set(paths.filter { $0.operation == nil }.map(pair)).count,193 operations: Set(paths.compactMap(\.operation)).count,194 availablePaths: paths.count,195 unavailablePaths: unavailableEngines.reduce(0) { $0 + $1.paths.count },196 engines: engines.count,197 unavailableEngines: unavailableEngines.count)198 }199200 // MARK: Matrix201202 /// Rows of the compatibility matrix: every available path, then the paths of unavailable engines.203 public func matrix() -> [MatrixRow] {204 func row(_ p: ConversionPath, unavailable reason: String?) -> MatrixRow {205 MatrixRow(source: p.source, destination: p.destination, operation: p.operation, engine: p.engine,206 status: reason == nil ? p.status.rawValue : "unavailable", fidelity: p.fidelity,207 preserves: p.preserves.map(\.rawValue).sorted(), limitations: p.limitations, unavailableReason: reason)208 }209 let missing = unavailableEngines.flatMap { engine in engine.paths.sorted(by: Self.pathOrder).map { row($0, unavailable: engine.reason) } }210 return paths.map { row($0, unavailable: nil) } + missing211 }212213 /// The matrix as a Markdown table (the body of `docs/compatibility/conversion-matrix.md`).214 public func matrixMarkdown() -> String {215 func cell(_ s: String) -> String { s.replacingOccurrences(of: "|", with: "\\|").replacingOccurrences(of: "\n", with: " ") }216 var out = "| Source | Destination | Operation | Engine | Status | Fidelity | Preserves | Limitations |\n"217 out += "|---|---|---|---|---|---|---|---|\n"218 for row in matrix() {219 var limitations = row.limitations220 if let reason = row.unavailableReason { limitations.insert("Unavailable: \(reason)", at: 0) }221 let cells = [222 row.source.rawValue, row.destination.rawValue, row.operation ?? "—", row.engine, row.status, row.fidelity.rawValue,223 row.preserves.isEmpty ? "—" : row.preserves.joined(separator: ", "),224 limitations.isEmpty ? "—" : limitations.joined(separator: "; "),225 ]226 out += "| " + cells.map(cell).joined(separator: " | ") + " |\n"227 }228 return out229 }230231 /// The matrix as pretty-printed JSON with stable key order: `{ "counts": …, "rows": [...] }`.232 public func matrixJSON() throws -> Data {233 struct Export: Codable { let counts: RegistryCounts; let rows: [MatrixRow] }234 let encoder = JSONEncoder()235 encoder.outputFormatting = [.prettyPrinted, .sortedKeys]236 return try encoder.encode(Export(counts: counts, rows: matrix()))237 }238}239