Repository Public License
1// ORIX Convert — Packages/ORIXConvertCore/Tests/ConvertCoreTests/DocSamplesTests.swift2// Description: The code samples of docs/development/core-api.md, compiled and executed against the mock engine so3// the documentation cannot drift from the API.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import Testing7@testable import ConvertCore89@Suite struct DocSamplesTests {10 @Test func coreAPISamples() async throws {11 let temp = TempDir("docs")12 let fileURL = temp.write("in/note.txt", "hello\n")13 let outputFolder = temp.subdirectory("out")14 let droppedURLs = [fileURL, temp.write("in/other.txt", "other\n")]15 let supportFolder = temp.subdirectory("support")16 let engines: [any ConversionEngine] = [TextEngine(), HTMLEngine()]1718 // --- sample: setup19 let history = try ConversionHistoryStore(url: supportFolder.appendingPathComponent("history.sqlite"))20 let manager = ConversionJobManager(engines: engines, history: history,21 workDirectories: WorkDirectoryManager(root: temp.file("work")))22 let registry = manager.registry23 let queue = manager.queue2425 // --- sample: detect and inspect26 let detection = FileTypeDetector.detect(fileURL)27 if detection.mismatch { print("Wrong extension: \(detection.evidence)") }28 let inspected = await manager.inspector.inspect(fileURL)29 _ = inspected.inspection.pixelWidth // nil when the engine could not read it3031 // --- sample: smart drop32 let analysis = await manager.smartDrop.analyze(droppedURLs)33 for group in analysis.groups {34 print(group.format?.rawValue ?? "unknown", group.urls.count, group.recommended.map(\.destination))35 }36 if let first = analysis.items.first {37 let (plan, warnings) = try manager.smartDrop.preflight(first, to: .markdown)38 print(plan.isChained, plan.fidelity, warnings.map(\.message))39 }4041 // --- sample: capabilities and planning42 let capabilities = manager.resolver.capabilities(for: .txt)43 _ = capabilities.recommended.map(\.destination)44 let plan = try manager.planner.plan(from: .txt, to: .html)45 _ = (plan.isChained, plan.intermediates, plan.limitations)4647 // --- sample: observe events48 let events = await queue.events()49 let observer = Task {50 for await event in events {51 switch event {52 case .jobAdded(let job), .jobChanged(let job): print(job.id, job.state)53 case .jobProgress(let id, let progress, let eta): print(id, progress.fraction ?? -1, eta ?? -1)54 case .jobLog(_, let line): print(line.date, line.level, line.message)55 case .jobWarning(_, let warning): print(warning.severity, warning.message)56 case .jobRemoved, .queueChanged, .idle: break57 }58 }59 }6061 // --- sample: enqueue62 let destination = OutputDestination(directory: outputFolder, nameTemplate: "{name}-{date}", conflictPolicy: .askUser)63 let jobIDs = await manager.convert(droppedURLs, to: .markdown, destination: destination)64 let single = await queue.enqueue(ConversionJobRequest(source: fileURL, to: .yaml, destination: destination, priority: .high))6566 // --- sample: control67 await queue.pause() // no new job starts; running jobs finish68 await queue.resume()69 _ = await queue.pauseJob(single) // only before the job starts70 _ = await queue.resumeJob(single)71 _ = await queue.setPriority(.low, for: single)72 _ = await queue.cancel(single)73 _ = await queue.retry(single)7475 // --- sample: wait and resolve conflicts76 for id in jobIDs + [single] {77 guard let job = await queue.waitForJob(id) else { continue }78 if job.state == .awaitingDecision, let conflict = job.conflict {79 print("Exists:", conflict.existing.path)80 _ = await queue.resolveConflict(id, policy: .rename) // or .replace / .skip81 }82 }83 await queue.waitUntilIdle()84 let snapshot = await queue.snapshot()85 print(snapshot.status.active, snapshot.jobs.map(\.state))8687 // --- sample: history88 var query = HistoryQuery()89 query.search = "note"90 query.statuses = ["finished"]91 query.limit = 5092 let entries = try await history.entries(query)93 try await history.delete(ids: entries.map(\.id))9495 // --- sample: presets96 let presets = PresetStore(fileURL: supportFolder.appendingPathComponent("presets.json"))97 await presets.registerBuiltIns([ConversionPreset(name: "Markdown", source: .format(.txt), destinationFormat: .markdown, isBuiltIn: true)])98 let preset = try await presets.add(ConversionPreset(name: "My YAML", source: .category(.document), destinationFormat: .yaml))99 _ = await manager.apply(preset, to: droppedURLs, destination: OutputDestination(directory: outputFolder))100101 // --- sample: workflow102 let workflow = Workflow(name: "Small notes to Markdown", nodes: [103 .filter(.all([.categoryIs(.document), .sizeBelow(1_000_000)])),104 .branch(condition: .nameMatches("draft-*"), then: [.rename(template: "{name}-draft")], otherwise: []),105 .convert(destination: .markdown, operation: nil, options: ConversionOptions()),106 .export(folder: outputFolder, conflictPolicy: .rename),107 ])108 let validation = WorkflowValidator.validate(workflow, registry: registry, inputFormats: [.txt])109 for issue in validation.issues { print(issue.severity, issue.nodePath, issue.message) }110 let library = WorkflowLibrary(fileURL: supportFolder.appendingPathComponent("workflows.json"))111 try await library.save(workflow)112 let run = try await manager.workflowRunner.run(workflow, inputs: droppedURLs) { item in113 print(item.source.lastPathComponent, item.status, item.outputs)114 }115 print(run.count(.succeeded), run.count(.failed), run.count(.filtered))116117 // --- sample: watch rule118 let watcher = FolderWatcher(runner: manager.workflowRunner, presets: presets, workflows: library,119 storeURL: supportFolder.appendingPathComponent("watch-rules.json"))120 let rule = WatchRule(name: "Inbox to Markdown", folder: fileURL.deletingLastPathComponent(), match: .formats([.txt]),121 action: .workflow(workflow.id), destinationFolder: outputFolder)122 do {123 let added = try await watcher.addRule(rule) // throws WatchError.loopRisk for a rule that feeds itself124 await watcher.start()125 try await watcher.setRulePaused(added.id, true)126 await watcher.stop()127 } catch let error as WatchError {128 print(error.localizedDescription)129 }130131 // --- sample: matrix132 let markdown = registry.matrixMarkdown()133 let json = try registry.matrixJSON()134 print(registry.counts.verifiedPairs, markdown.count, json.count)135136 observer.cancel()137 // The samples really ran.138 #expect(run.count(.succeeded) == 2)139 #expect(temp.list("out").contains("note.md") && validation.isValid)140 }141}142