| 1 | import Foundation |
| 2 | import Testing |
| 3 | @testable import EquipoKit |
| 4 | |
| 5 | struct MarkdownGolden: Codable { |
| 6 | var name: String |
| 7 | var source: String |
| 8 | var draft: Bool |
| 9 | var tree: [ChatMarkdownNode] |
| 10 | } |
| 11 | |
| 12 | @Suite struct ChatMarkdownTests { |
| 13 | @Test func linksFollowTheWebPolicyAndOnlyLocalTasksNavigateInApp() { |
| 14 | let origin = URL(string: "https://team.example.test")! |
| 15 | #expect(MarkdownActions.destination("/tasks/tkabc123", origin: origin) == .task("tkabc123")) |
| 16 | #expect(MarkdownActions.destination("/projects/p_abc", origin: origin) == .external(origin.appendingPathComponent("projects/p_abc"))) |
| 17 | for target in ["https://other.test/path", "http://other.test", "mailto:person@example.test", "https://team.example.test/tasks/tkabc"] { |
| 18 | #expect(MarkdownActions.destination(target, origin: origin) == .external(URL(string: target)!)) |
| 19 | } |
| 20 | for target in ["file:/tmp/x", "ftp://x", "tel:1", "sms:1", "blob:https://x", "vbscript:x", "custom:x", "javascript:alert(1)", "data:text/html,evil", "//evil.test", "/settings", "/tasks/tkabc?x=1", "/tasks/tkabc/../../logout", "/tasks/TKabc", "/tasks/tkabc%00", "https://example.test/%xx"] { |
| 21 | #expect(MarkdownActions.destination(target, origin: origin) == nil) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | @Test func blankCodeLinesPreserveOriginalBytesInLinearTime() throws { |
| 26 | let block = "```ts\nconst a = 1\n\nfoo[i](<T<U>>x)\n```\n" |
| 27 | let clock = ContinuousClock() |
| 28 | let start = clock.now |
| 29 | let tree = ChatMarkdown.parse(String(repeating: block, count: 3000), draft: false) |
| 30 | #expect(tree.count == 3000) |
| 31 | #expect(tree.allSatisfy { MarkdownActions.copyText($0) == "const a = 1\n\nfoo[i](<T<U>>x)" }) |
| 32 | #expect(start.duration(to: clock.now) < .seconds(2)) |
| 33 | } |
| 34 | |
| 35 | @Test func schemePolicyIsAnExactAllowlist() { |
| 36 | #expect(MarkdownLinks.schemes == ["http", "https", "mailto"]) |
| 37 | // Valid scheme grammar, arbitrary suffixes and case variants. The |
| 38 | // property is membership, independent of authority/path validation. |
| 39 | var schemes = ["http", "https", "mailto", "webcal", "file", "ftp", "tel", "sms", "blob", "vbscript", "custom"] |
| 40 | for first in "abcdefghijklmnopqrstuvwxyz" { |
| 41 | for tail in ["", "+x", "-1", ".test", "0", "http", "mailto"] { |
| 42 | schemes.append(String(first) + tail) |
| 43 | } |
| 44 | } |
| 45 | for scheme in schemes { |
| 46 | for variant in [scheme, scheme.uppercased(), scheme.capitalized] { |
| 47 | let expected = ["http", "https", "mailto"].contains(scheme) |
| 48 | for suffix in ["opaque", "//example.test/path", "a@b.test"] { |
| 49 | #expect(ChatMarkdown.allowsLink(variant + ":" + suffix) == expected) |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | @Test func syntaxInsideALabelCannotChangeItsDestination() { |
| 56 | let source = "[`x](https://evil.test)`](https://good.test/x)" |
| 57 | let tree = ChatMarkdown.parse(source, draft: false) |
| 58 | #expect(tree.first?.children.first?.target == "https://good.test/x") |
| 59 | } |
| 60 | |
| 61 | @Test func oddButWebAllowedHostsHaveActionableNativeURLs() { |
| 62 | let origin = URL(string: "https://team.example.test")! |
| 63 | for (raw, escaped) in [("http://]", "http://%5D"), ("https://\";", "https://%22;")] { |
| 64 | #expect(MarkdownActions.destination(raw, origin: origin) == .external(URL(string: escaped)!)) |
| 65 | // The encoded URL was never itself allowed by the web. The view |
| 66 | // must resolve it through its actual rendered link's original target. |
| 67 | #expect(!ChatMarkdown.allowsLink(escaped)) |
| 68 | let tree = ChatMarkdown.parse("[x](" + raw + ")", draft: false) |
| 69 | #expect(MarkdownActions.originalTarget(URL(string: escaped)!, in: tree) == raw) |
| 70 | #expect(MarkdownActions.originalTarget(URL(string: "https://evil.test")!, in: tree) == nil) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | @Test func copyWaitsForClosureAndDropsOnlyTheLastNewline() throws { |
| 75 | let source = "```sh\nls & <x> \n\n" |
| 76 | let open = try #require(ChatMarkdown.parse(source, draft: true).first) |
| 77 | #expect(MarkdownActions.copyText(open) == nil) |
| 78 | let closed = try #require(ChatMarkdown.parse(source + "```\n", draft: true).first) |
| 79 | #expect(MarkdownActions.copyText(closed) == "ls & <x> \n") |
| 80 | var expected = open |
| 81 | expected.copyEnabled = true |
| 82 | #expect(closed == expected, "closing a fence changes only Copy availability") |
| 83 | #expect(MarkdownActions.copyText(ChatMarkdownNode(kind: "text", text: "ordinary prose")) == nil) |
| 84 | let finished = try #require(ChatMarkdown.parse(source, draft: false).first) |
| 85 | #expect(MarkdownActions.copyText(finished) == "ls & <x> \n") |
| 86 | } |
| 87 | |
| 88 | @Test func deepQuotesOnPhoneSizedStack() async { |
| 89 | await withCheckedContinuation { continuation in |
| 90 | let worker = Thread { |
| 91 | for depth in [200, 1000, 5000] { |
| 92 | let tree = ChatMarkdown.parse(String(repeating: "> ", count: depth) + "x", draft: false) |
| 93 | #expect(tree == [ChatMarkdownNode(kind: "paragraph", children: [ChatMarkdownNode(kind: "text", text: "x")])]) |
| 94 | } |
| 95 | continuation.resume() |
| 96 | } |
| 97 | worker.stackSize = 1024 * 1024 |
| 98 | worker.start() |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | @Test func draftMarkerScanHasLinearCost() { |
| 103 | let clock = ContinuousClock() |
| 104 | let elapsed = clock.measure { |
| 105 | for count in [800, 1600, 3200] { |
| 106 | let text = String(repeating: " ", count: count) + "x" |
| 107 | #expect(MarkdownDraft.steady(text) == text) |
| 108 | } |
| 109 | } |
| 110 | #expect(elapsed < .seconds(1)) |
| 111 | } |
| 112 | |
| 113 | @MainActor @Test func backgroundParsingLeavesTheMainThread() async { |
| 114 | let result = await ChatMarkdown.parseInBackground("**hello**", draft: false) |
| 115 | #expect(result.first?.children.first?.kind == "strong") |
| 116 | } |
| 117 | |
| 118 | @Test func manyReferencesAreScannedOnce() { |
| 119 | let source = (0..<2000).map { "[label\($0)][r]" }.joined(separator: " ") + "\n\n[r]: https://good.test/x" |
| 120 | let clock = ContinuousClock() |
| 121 | let start = clock.now |
| 122 | let tree = ChatMarkdown.parse(source, draft: false) |
| 123 | #expect(tree.first?.children.filter { $0.kind == "link" }.count == 2000) |
| 124 | #expect(start.duration(to: clock.now) < .seconds(2)) |
| 125 | } |
| 126 | |
| 127 | @Test func dependencyAndUserVisibleNoticeStayWired() throws { |
| 128 | let apple = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() |
| 129 | let manifest = try String(contentsOf: apple.appendingPathComponent("Package.swift"), encoding: .utf8) |
| 130 | #expect(manifest.contains("revision: \"08ddb528923cc1a6527e02b7a1aee9e516ca749a\"")) |
| 131 | let account = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/UI/Screens/AccountScreen.swift"), encoding: .utf8) |
| 132 | #expect(account.contains("MarkdownNotices()")) |
| 133 | let renderer = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/ChatMarkdownView.swift"), encoding: .utf8) |
| 134 | #expect(renderer.contains(".accessibilityLabel(Text(verbatim: MarkdownPresentation.pasteLabel(node)))")) |
| 135 | let streaming = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/MarkdownStreamRenderer.swift"), encoding: .utf8) |
| 136 | #expect(streaming.contains("await ChatMarkdown.parseInBackground")) |
| 137 | #expect(renderer.contains(".onChange(of: request)")) |
| 138 | #expect(renderer.contains(".onAppear {")) |
| 139 | #expect(!renderer.contains(".onDisappear")) |
| 140 | #expect(renderer.contains("stream = transcript.renderer(for: request.messageID)")) |
| 141 | let strings = try String(contentsOf: apple.deletingLastPathComponent().appendingPathComponent("scripts/strings.json"), encoding: .utf8) |
| 142 | #expect(!strings.contains("message.coordinator_spoken")) |
| 143 | let parser = try String(contentsOf: apple.appendingPathComponent("Sources/EquipoKit/Markdown/ChatMarkdown.swift"), encoding: .utf8) |
| 144 | let linkFunction = parser.components(separatedBy: "func linkTarget").last!.components(separatedBy: "func textValue").first! |
| 145 | #expect(!linkFunction.contains("NSRegularExpression")) |
| 146 | #expect(!linkFunction.contains("matches(in: source")) |
| 147 | } |
| 148 | |
| 149 | @Test func matchesEveryWebGolden() throws { |
| 150 | var fixtures = try JSONDecoder().decode([MarkdownGolden].self, from: Fixture.data("markdown/golden")) |
| 151 | if let path = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_DIFFERENTIAL"] { |
| 152 | let generated = try JSONDecoder().decode([MarkdownGolden].self, from: Data(contentsOf: URL(fileURLWithPath: path))) |
| 153 | #expect(generated.count >= 20_000) |
| 154 | #expect(Set(generated.map(\.source)).count == generated.count) |
| 155 | fixtures += generated |
| 156 | } |
| 157 | var failures = 0 |
| 158 | var actual = fixtures |
| 159 | for (index, fixture) in fixtures.enumerated() { |
| 160 | let tree = ChatMarkdown.parse(fixture.source, draft: fixture.draft) |
| 161 | func controls(_ values: [ChatMarkdownNode]) -> [UInt8] { |
| 162 | var pending = values, result: [UInt8] = [] |
| 163 | while let item = pending.popLast() { |
| 164 | result += (item.text ?? "").utf8.filter { (1...8).contains($0) || $0 == 127 } |
| 165 | pending += item.children |
| 166 | } |
| 167 | return result.sorted() |
| 168 | } |
| 169 | #expect(controls(tree) == controls(fixture.tree), "introduced placeholder in \(fixture.name)") |
| 170 | actual[index].tree = tree |
| 171 | if tree != fixture.tree { |
| 172 | failures += 1 |
| 173 | if failures <= 5 { Issue.record("\(fixture.name): \(String(reflecting: fixture.source))\nactual: \(tree)\nexpected: \(fixture.tree)") } |
| 174 | } |
| 175 | } |
| 176 | #expect(failures == 0, "\(failures) of \(fixtures.count) web fixtures differ") |
| 177 | if let path = ProcessInfo.processInfo.environment["EQUIPO_MARKDOWN_ACTUAL"] { |
| 178 | try JSONEncoder().encode(actual).write(to: URL(fileURLWithPath: path)) |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |