// Spike (#74) — THROWAWAY. apex → HTML → WKWebView reading surface. // Proves: data-source-line mapping, CSS-var typography, ⌘-click links, in-app apex latency, first paint. import AppKit import SwiftUI import WebKit // MARK: - Mapping (pure, self-checked) /// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after. enum MarkdownChunker { /// Prepend `` (N = 1-based source line) before every blank-line chunk. nonisolated static func stamp(_ source: String) -> String { let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } } let lines = source.split(separator: "\n", omittingEmptySubsequences: false) var out: [String] = [] var i = 0 while i < lines.count { if isBlank(lines[i]) { i += 1; continue } if !out.isEmpty { out.append("") } out.append("") while i < lines.count, !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 } } return out.joined(separator: "\n") } } /// Rewrites `` into `data-source-line="N"` on the element that follows. enum HTMLStamper { nonisolated static func stamp(_ html: String) -> String { let re = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#) let ms = NSMutableString(string: html) re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"") return ms as String } } // MARK: - Apex runner enum Apex { nonisolated static func binaryPath() -> String? { if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env } for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) { return p } return nil } /// markdown → HTML fragment with images embedded (base64). Returns (html, milliseconds). nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) { guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) } let t0 = DispatchTime.now() let p = Process() p.executableURL = URL(fileURLWithPath: bin) // --no-mixed-lists: apex default merges an ordered list after a bullet list into one