Commit 50415157d2

50415157d2651527e633b620a4c82a8e2232a80a

parent: 6f0eeeeea0

Unsigned

cmc <hello@cleberg.net> · 2026-10-25 06:22 UTC

Move the export formatters out of the view model (!33)

A13's remaining file — but not by the route the task assumed, and I want to be
direct about why.

## Collapsing A2's model duplication would not have worked

That was the premise: finish A2 so `DomainViewModel` can be split. Measured, it
is 12% of the problem.

| cluster | lines |
|---|---|
| lookup orchestration, tracking, state | 2,047 |
| **snapshot/entry/report conversion** | **455** |
| portfolio and dashboard | 426 |
| batch pipeline | 351 |
| export formatting | 330 |
| section row builders | 209 |
| audit | 103 |

Removing all 455 lines of the duplication would not approach a 210 budget, and
it is the riskiest change in the codebase: `HistoryEntry` is the persisted
format, on the path that can lose a user's data. Spending that risk to move a
lint threshold would have been a poor trade even if it worked.

## What did work

The 16 static export formatters move with no instance state involved:
complexity **370 → 280**, the file 3,934 → 3,571 lines, and the ratchet
**380 → 290**. Verified both ways as usual: clean at 290, `DomainViewModel`
fails at 270.

Bodies are unchanged — checked line-for-line against `git show HEAD:`. The only
declaration changes are six `private static` helpers becoming internal, because
code left behind still calls them: `availabilityLabel`, `durationLabel`,
`emailSummary`, `finalRedirectTarget`, `httpsSummary`, `primaryIPAddress`. I
checked each one's usage individually rather than widening on sight; two that
only the exporters used (`csvDateFormatter`, `csvEscaped`) moved with them
instead.

## Why batch and portfolio stay

Swift extensions cannot hold stored properties. The batch pipeline writes six
`private(set)` properties and portfolio writes two private caches, so moving
either means making that state settable from any file in the module. That
trades real encapsulation for a smaller number in a config file.

Extracting them as types that own their own state is the right answer and would
take the threshold near 200. It is a design change, not a file move, so it
belongs in its own piece of work.

## A14, found by a failed assertion

Four files declare a private `String.nilIfEmpty`, and they are **not the same
function** — `DomainInsightEngine`'s trims whitespace first, so `"   "` becomes
`nil` there and stays `"   "` everywhere else. I tried the obvious tidy-up
(hoist one to internal, delete the rest); the dedup assertion failed on the
text not matching, and only then did the difference show. Had the strings
matched, I would have changed `DomainInsightEngine`'s behaviour silently, with
nothing covering it.

They stay separate, the export file keeps its own non-trimming copy, and the
finding says the fix is to name them for what they do rather than unify them.

## Verification

244 tests, 0 failures on iOS 18.6 (iPhone 16) and iOS 27.0 (iPhone Air).

Layout: unified · split

.qlty/qlty.toml +12 −9
@@ -44,15 +44,18 @@ enabled = false
4444# above today's worst file and fails anything past it. Lower it when a file is
4545# genuinely split, never raise it to make a commit pass.
4646#
47# Measured after the A13 splits: DomainViewModel 370, CloudSyncService 198,
48# WatchlistView 146, DomainDataPortabilityService 146, AuditViews 128,
49# ContentView 119, DomainDiffViews 115, DomainReportExporter 114,
50# SettingsViews 112, WorkflowsView 107.
47# Measured after moving DomainViewModel's export formatters out:
48# DomainViewModel 280, CloudSyncService 198, WatchlistView 146,
49# DomainDataPortabilityService 146, AuditViews 128, ContentView 119,
50# DomainDiffViews 115, DomainReportExporter 114, SettingsViews 112,
51# WorkflowsView 107.
5152#
52# DomainViewModel alone holds this threshold where it is — the next file is 172
53# points below it. Splitting it would let this drop to about 210, and it is the
54# hard one: A2 collapsed its section state but left the four-way model
55# duplication that makes it long.
53# DomainViewModel still holds this threshold where it is. Getting below about
54# 200 needs batch and portfolio out of it, and neither is a file move: Swift
55# extensions cannot hold stored properties, so the batch pipeline's six
56# `private(set)` properties and the portfolio caches would have to become
57# settable from any file. That trades real encapsulation for a lint number.
58# Extracting them as types that own their state is the way; see A13.
5659[smells.file_complexity]
5760enabled = true
5861
@@ -81,4 +84,4 @@ filter_patterns = [
8184]
8285
8386[language.swift.smells.file_complexity]
84threshold = 380
87threshold = 290
DomainDig/DomainViewModel+Export.swift +384
@@ -189,3 +189,387 @@ private struct WorkflowExportPayload: Codable {
189189 let workflowInsights: [WorkflowInsight]
190190 let reports: [DomainReport]
191191}
192
193// MARK: - Export line builders
194
195// Moved out of DomainViewModel.swift (A13): these are static functions
196// over a snapshot or report, so they hold no view-model state and the
197// core file was carrying a quarter of its length in them.
198
199extension DomainViewModel {
200 static func formatBatchExportText(
201 title: String,
202 entries: [(snapshot: LookupSnapshot, trackedDomain: TrackedDomain?, changeSummary: DomainChangeSummary?, diffSections: [DomainDiffSection])]
203 ) -> String {
204 guard !entries.isEmpty else {
205 return "\(title)\nNo results available."
206 }
207
208 var lines = [title, String(repeating: "=", count: title.count), ""]
209 for (index, entry) in entries.enumerated() {
210 if index > 0 {
211 lines.append("")
212 lines.append(String(repeating: "=", count: 48))
213 lines.append("")
214 }
215
216 lines.append(
217 formatExportText(
218 from: entry.snapshot,
219 trackedDomain: entry.trackedDomain,
220 changeSummary: entry.changeSummary,
221 diffSections: entry.diffSections
222 )
223 )
224 }
225 return lines.joined(separator: "\n")
226 }
227
228 static func formatCSV(from snapshots: [LookupSnapshot]) -> String {
229 let headers = [
230 "domain",
231 "availability",
232 "primary_ip",
233 "redirect_target",
234 "tls_status",
235 "http_status_grade",
236 "email_security_summary",
237 "registrar",
238 "ownership_expires",
239 "ownership_status",
240 "ownership_nameservers",
241 "subdomain_count",
242 "subdomains",
243 "last_updated"
244 ]
245
246 let rows = snapshots.map { snapshot in
247 [
248 snapshot.domain,
249 availabilityLabel(snapshot.availabilityResult?.status),
250 primaryIPAddress(from: snapshot) ?? "",
251 finalRedirectTarget(from: snapshot) ?? "",
252 httpsSummary(from: snapshot),
253 httpStatusGradeSummary(from: snapshot),
254 emailSummary(from: snapshot),
255 snapshot.ownership?.registrar ?? "",
256 snapshot.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? "",
257 snapshot.ownership?.status.joined(separator: " | ") ?? "",
258 snapshot.ownership?.nameservers.joined(separator: " | ") ?? "",
259 "\(snapshot.subdomains.count)",
260 snapshot.subdomains.map(\.hostname).joined(separator: " | "),
261 csvDateFormatter.string(from: snapshot.timestamp)
262 ]
263 }
264
265 return ([headers] + rows)
266 .map { row in row.map(csvEscaped).joined(separator: ",") }
267 .joined(separator: "\n")
268 }
269
270 static func formatExportText(
271 from snapshot: LookupSnapshot,
272 trackedDomain: TrackedDomain?,
273 changeSummary: DomainChangeSummary?,
274 diffSections: [DomainDiffSection]
275 ) -> String {
276 let exportDateFormatter = DateFormatter()
277 exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
278
279 var lines: [String] = [
280 "DomainDig Export",
281 "Domain: \(snapshot.domain)",
282 "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
283 "Mode: \(snapshot.statusMessage ?? snapshot.resultSource.label)",
284 "Resolver: \(snapshot.resolverDisplayName)",
285 "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))",
286 "Tracked: \(trackedDomain == nil ? "No" : "Yes")"
287 ]
288
289 if let note = trackedDomain?.note?.nilIfEmpty {
290 lines.append("Tracking Note: \(note)")
291 }
292
293 func appendSection(_ title: String, _ body: [String]) {
294 lines.append("")
295 lines.append(title)
296 lines.append(String(repeating: "-", count: title.count))
297 lines += body
298 }
299
300 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
301 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
302 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
303 appendSection("Domain", exportDomainLines(snapshot))
304 appendSection("Ownership", exportOwnershipLines(snapshot))
305 appendSection("Subdomains", exportSubdomainsLines(snapshot))
306 appendSection("DNS", exportDnsLines(snapshot))
307 appendSection("Web", exportWebLines(snapshot))
308 appendSection("Email", exportEmailLines(snapshot))
309 appendSection("Network", exportNetworkLines(snapshot))
310
311 return lines.joined(separator: "\n")
312 }
313
314 private static func exportSummaryLines(
315 _ snapshot: LookupSnapshot,
316 changeSummary: DomainChangeSummary?,
317 exportDateFormatter: DateFormatter
318 ) -> [String] {
319 var lines: [String] = []
320 for item in summaryFields(from: snapshot) {
321 lines.append(" \(item.label): \(item.value)")
322 }
323 if let changeSummary {
324 lines.append(" Change Summary: \(changeSummary.message)")
325 lines.append(" Severity: \(changeSummary.severity.title)")
326 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
327 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
328 }
329 return lines
330 }
331
332 private static func exportTrackingLines(_ trackedDomain: TrackedDomain?, exportDateFormatter: DateFormatter) -> [String] {
333 var lines: [String] = []
334 if let trackedDomain {
335 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
336 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
337 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
338 if let note = trackedDomain.note?.nilIfEmpty {
339 lines.append(" Note: \(note)")
340 }
341 } else {
342 lines.append(" This domain is not currently tracked.")
343 }
344 return lines
345 }
346
347 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
348 var lines: [String] = []
349 if diffSections.isEmpty {
350 lines.append(" No comparison available")
351 } else {
352 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
353 lines.append(" \(section.title)")
354 for item in section.items where item.changeType != .unchanged {
355 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
356 }
357 }
358 }
359 return lines
360 }
361
362 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
363 var lines: [String] = []
364 for row in domainRows(from: snapshot) {
365 lines.append(" \(row.label): \(row.value)")
366 }
367 if snapshot.suggestions.isEmpty {
368 lines.append(" Suggestions: None")
369 } else {
370 lines.append(" Suggestions:")
371 for suggestion in snapshot.suggestions {
372 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
373 }
374 }
375 return lines
376 }
377
378 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
379 var lines: [String] = []
380 for row in ownershipRows(from: snapshot) {
381 lines.append(" \(row.label): \(row.value)")
382 }
383 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
384 lines.append(" Source: \(ownershipError)")
385 }
386 return lines
387 }
388
389 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
390 var lines: [String] = []
391 lines.append(" Count: \(snapshot.subdomains.count)")
392 if snapshot.subdomains.isEmpty {
393 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
394 } else {
395 for subdomain in subdomainRows(from: snapshot) {
396 let marker = subdomain.isInteresting ? " [interesting]" : ""
397 lines.append(" \(subdomain.hostname)\(marker)")
398 }
399 }
400 if !FeatureAccessService.hasAccess(to: .extendedSubdomains) {
401 lines.append(" Extended subdomain discovery (Pro)")
402 }
403 return lines
404 }
405
406 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
407 var lines: [String] = []
408 if let dnsError = snapshot.dnsError {
409 lines.append(" Error: \(dnsError)")
410 }
411 if let dnssecLabel = dnssecLabel(from: snapshot) {
412 lines.append(" \(dnssecLabel)")
413 }
414 for section in dnsRows(from: snapshot) {
415 lines += exportDNSSectionLines(section)
416 }
417 if let ptrRecord = snapshot.ptrRecord {
418 lines.append(" PTR: \(ptrRecord)")
419 } else if let ptrError = snapshot.ptrError {
420 lines.append(" PTR Error: \(ptrError)")
421 }
422 return lines
423 }
424
425 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
426 var lines = [" \(section.title)"]
427 if let message = section.message {
428 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
429 }
430 for row in section.rows {
431 lines.append(" \(row.value) (\(row.label))")
432 }
433 if let wildcardTitle = section.wildcardTitle {
434 lines.append(" \(wildcardTitle)")
435 for row in section.wildcardRows {
436 lines.append(" \(row.value) (\(row.label))")
437 }
438 }
439 return lines
440 }
441
442 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
443 if let httpHeadersError = snapshot.httpHeadersError {
444 return [" Headers Error: \(httpHeadersError)"]
445 }
446 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
447 if snapshot.httpHeaders.isEmpty {
448 lines.append(" Headers: No headers returned")
449 } else {
450 lines.append(" Headers:")
451 for header in snapshot.httpHeaders {
452 lines.append(" \(header.name): \(header.value)")
453 }
454 }
455 return lines
456 }
457
458 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
459 var lines: [String] = []
460 if let sslError = snapshot.sslError {
461 lines.append(" TLS Error: \(sslError)")
462 } else {
463 for row in webCertificateRows(from: snapshot) {
464 lines.append(" \(row.label): \(row.value)")
465 }
466 }
467 lines += exportResponseLines(snapshot)
468
469 if let redirectChainError = snapshot.redirectChainError {
470 lines.append(" Redirect Error: \(redirectChainError)")
471 } else if snapshot.redirectChain.isEmpty {
472 lines.append(" Redirects: No redirect data available")
473 } else {
474 lines.append(" Redirects:")
475 for hop in redirectRows(from: snapshot) {
476 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
477 }
478 }
479 return lines
480 }
481
482 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
483 var lines: [String] = []
484 if let emailSecurityError = snapshot.emailSecurityError {
485 lines.append(" Error: \(emailSecurityError)")
486 } else if emailRows(from: snapshot).isEmpty {
487 lines.append(" No email security records found")
488 } else {
489 for row in emailRows(from: snapshot) {
490 lines.append(" \(row.label): \(row.status)")
491 lines.append(" \(row.detail)")
492 if let auxiliaryDetail = row.auxiliaryDetail {
493 lines.append(" \(auxiliaryDetail)")
494 }
495 }
496 }
497 return lines
498 }
499
500 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
501 guard !rows.isEmpty else { return [" No results"] }
502 var lines: [String] = []
503 for row in rows {
504 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
505 if let banner = row.banner {
506 lines.append(" Banner: \(banner)")
507 }
508 }
509 return lines
510 }
511
512 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
513 var lines: [String] = []
514 if let reachabilityError = snapshot.reachabilityError {
515 lines.append(" Reachability Error: \(reachabilityError)")
516 } else if reachabilityRows(from: snapshot).isEmpty {
517 lines.append(" Reachability: No results")
518 } else {
519 lines.append(" Reachability:")
520 for row in reachabilityRows(from: snapshot) {
521 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
522 }
523 }
524
525 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
526 lines.append(" Location Error: \(ipGeolocationError)")
527 } else if locationRows(from: snapshot).isEmpty {
528 lines.append(" Location: No data")
529 } else {
530 lines.append(" Location:")
531 for row in locationRows(from: snapshot) {
532 lines.append(" \(row.label): \(row.value)")
533 }
534 }
535
536 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
537 lines.append(" Port Scan Error: \(portScanError)")
538 }
539
540 lines.append(" Standard Ports:")
541 lines += exportPortLines(portRows(from: snapshot, kind: .standard))
542 lines.append(" Custom Ports:")
543 lines += exportPortLines(portRows(from: snapshot, kind: .custom))
544 return lines
545 }
546
547 private static let csvDateFormatter: ISO8601DateFormatter = {
548 let formatter = ISO8601DateFormatter()
549 formatter.formatOptions = [.withInternetDateTime]
550 return formatter
551 }()
552
553 private static func csvEscaped(_ value: String) -> String {
554 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
555 return "\"\(escaped)\""
556 }
557
558 private static func httpStatusGradeSummary(from snapshot: LookupSnapshot) -> String {
559 let parts = [snapshot.httpStatusCode.map(String.init), snapshot.httpSecurityGrade].compactMap { $0 }
560 if !parts.isEmpty {
561 return parts.joined(separator: " / ")
562 }
563 return snapshot.httpHeadersError ?? "Unavailable"
564 }
565}
566
567// Deliberately a private copy rather than a shared one. `nilIfEmpty` means two
568// different things in this codebase: DomainInsightEngine's trims whitespace
569// first, every other copy does not. The exporters moved here were using the
570// non-trimming version, so that is what they keep (A14).
571private extension String {
572 var nilIfEmpty: String? {
573 isEmpty ? nil : self
574 }
575}
DomainDig/DomainViewModel.swift +9 −372
@@ -3379,370 +3379,15 @@ final class DomainViewModel {
33793379 }
33803380 }
33813381
3382 static func formatBatchExportText(
3383 title: String,
3384 entries: [(snapshot: LookupSnapshot, trackedDomain: TrackedDomain?, changeSummary: DomainChangeSummary?, diffSections: [DomainDiffSection])]
3385 ) -> String {
3386 guard !entries.isEmpty else {
3387 return "\(title)\nNo results available."
3388 }
3389
3390 var lines = [title, String(repeating: "=", count: title.count), ""]
3391 for (index, entry) in entries.enumerated() {
3392 if index > 0 {
3393 lines.append("")
3394 lines.append(String(repeating: "=", count: 48))
3395 lines.append("")
3396 }
3397
3398 lines.append(
3399 formatExportText(
3400 from: entry.snapshot,
3401 trackedDomain: entry.trackedDomain,
3402 changeSummary: entry.changeSummary,
3403 diffSections: entry.diffSections
3404 )
3405 )
3406 }
3407 return lines.joined(separator: "\n")
3408 }
3409
3410 static func formatCSV(from snapshots: [LookupSnapshot]) -> String {
3411 let headers = [
3412 "domain",
3413 "availability",
3414 "primary_ip",
3415 "redirect_target",
3416 "tls_status",
3417 "http_status_grade",
3418 "email_security_summary",
3419 "registrar",
3420 "ownership_expires",
3421 "ownership_status",
3422 "ownership_nameservers",
3423 "subdomain_count",
3424 "subdomains",
3425 "last_updated"
3426 ]
3427
3428 let rows = snapshots.map { snapshot in
3429 [
3430 snapshot.domain,
3431 availabilityLabel(snapshot.availabilityResult?.status),
3432 primaryIPAddress(from: snapshot) ?? "",
3433 finalRedirectTarget(from: snapshot) ?? "",
3434 httpsSummary(from: snapshot),
3435 httpStatusGradeSummary(from: snapshot),
3436 emailSummary(from: snapshot),
3437 snapshot.ownership?.registrar ?? "",
3438 snapshot.ownership?.expirationDate.map(csvDateFormatter.string(from:)) ?? "",
3439 snapshot.ownership?.status.joined(separator: " | ") ?? "",
3440 snapshot.ownership?.nameservers.joined(separator: " | ") ?? "",
3441 "\(snapshot.subdomains.count)",
3442 snapshot.subdomains.map(\.hostname).joined(separator: " | "),
3443 csvDateFormatter.string(from: snapshot.timestamp)
3444 ]
3445 }
3446
3447 return ([headers] + rows)
3448 .map { row in row.map(csvEscaped).joined(separator: ",") }
3449 .joined(separator: "\n")
3450 }
3451
3452 static func formatExportText(
3453 from snapshot: LookupSnapshot,
3454 trackedDomain: TrackedDomain?,
3455 changeSummary: DomainChangeSummary?,
3456 diffSections: [DomainDiffSection]
3457 ) -> String {
3458 let exportDateFormatter = DateFormatter()
3459 exportDateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
3460
3461 var lines: [String] = [
3462 "DomainDig Export",
3463 "Domain: \(snapshot.domain)",
3464 "Date: \(exportDateFormatter.string(from: snapshot.timestamp))",
3465 "Mode: \(snapshot.statusMessage ?? snapshot.resultSource.label)",
3466 "Resolver: \(snapshot.resolverDisplayName)",
3467 "Lookup Duration: \(durationLabel(snapshot.totalLookupDurationMs))",
3468 "Tracked: \(trackedDomain == nil ? "No" : "Yes")"
3469 ]
3470
3471 if let note = trackedDomain?.note?.nilIfEmpty {
3472 lines.append("Tracking Note: \(note)")
3473 }
3474
3475 func appendSection(_ title: String, _ body: [String]) {
3476 lines.append("")
3477 lines.append(title)
3478 lines.append(String(repeating: "-", count: title.count))
3479 lines += body
3480 }
3481
3482 appendSection("Summary", exportSummaryLines(snapshot, changeSummary: changeSummary, exportDateFormatter: exportDateFormatter))
3483 appendSection("Tracking", exportTrackingLines(trackedDomain, exportDateFormatter: exportDateFormatter))
3484 appendSection("Diff Summary", exportDiffSummaryLines(diffSections))
3485 appendSection("Domain", exportDomainLines(snapshot))
3486 appendSection("Ownership", exportOwnershipLines(snapshot))
3487 appendSection("Subdomains", exportSubdomainsLines(snapshot))
3488 appendSection("DNS", exportDnsLines(snapshot))
3489 appendSection("Web", exportWebLines(snapshot))
3490 appendSection("Email", exportEmailLines(snapshot))
3491 appendSection("Network", exportNetworkLines(snapshot))
3492
3493 return lines.joined(separator: "\n")
3494 }
3495
3496 private static func exportSummaryLines(
3497 _ snapshot: LookupSnapshot,
3498 changeSummary: DomainChangeSummary?,
3499 exportDateFormatter: DateFormatter
3500 ) -> [String] {
3501 var lines: [String] = []
3502 for item in summaryFields(from: snapshot) {
3503 lines.append(" \(item.label): \(item.value)")
3504 }
3505 if let changeSummary {
3506 lines.append(" Change Summary: \(changeSummary.message)")
3507 lines.append(" Severity: \(changeSummary.severity.title)")
3508 lines.append(" Changed Sections: \(changeSummary.changedSections.isEmpty ? "None" : changeSummary.changedSections.joined(separator: ", "))")
3509 lines.append(" Compared At: \(exportDateFormatter.string(from: changeSummary.generatedAt))")
3510 }
3511 return lines
3512 }
3513
3514 private static func exportTrackingLines(_ trackedDomain: TrackedDomain?, exportDateFormatter: DateFormatter) -> [String] {
3515 var lines: [String] = []
3516 if let trackedDomain {
3517 lines.append(" Pinned: \(trackedDomain.isPinned ? "Yes" : "No")")
3518 lines.append(" Last Refresh: \(exportDateFormatter.string(from: trackedDomain.updatedAt))")
3519 lines.append(" Last Known Availability: \(availabilityLabel(trackedDomain.lastKnownAvailability))")
3520 if let note = trackedDomain.note?.nilIfEmpty {
3521 lines.append(" Note: \(note)")
3522 }
3523 } else {
3524 lines.append(" This domain is not currently tracked.")
3525 }
3526 return lines
3527 }
3528
3529 private static func exportDiffSummaryLines(_ diffSections: [DomainDiffSection]) -> [String] {
3530 var lines: [String] = []
3531 if diffSections.isEmpty {
3532 lines.append(" No comparison available")
3533 } else {
3534 for section in diffSections where section.items.contains(where: { $0.changeType != .unchanged }) {
3535 lines.append(" \(section.title)")
3536 for item in section.items where item.changeType != .unchanged {
3537 lines.append(" [\(item.changeType.rawValue.capitalized)] \(item.label): \(item.oldValue ?? "None") -> \(item.newValue ?? "None")")
3538 }
3539 }
3540 }
3541 return lines
3542 }
3543
3544 private static func exportDomainLines(_ snapshot: LookupSnapshot) -> [String] {
3545 var lines: [String] = []
3546 for row in domainRows(from: snapshot) {
3547 lines.append(" \(row.label): \(row.value)")
3548 }
3549 if snapshot.suggestions.isEmpty {
3550 lines.append(" Suggestions: None")
3551 } else {
3552 lines.append(" Suggestions:")
3553 for suggestion in snapshot.suggestions {
3554 lines.append(" \(suggestion.domain): \(availabilityLabel(suggestion.status))")
3555 }
3556 }
3557 return lines
3558 }
3559
3560 private static func exportOwnershipLines(_ snapshot: LookupSnapshot) -> [String] {
3561 var lines: [String] = []
3562 for row in ownershipRows(from: snapshot) {
3563 lines.append(" \(row.label): \(row.value)")
3564 }
3565 if let ownershipError = snapshot.ownershipError, snapshot.ownership == nil {
3566 lines.append(" Source: \(ownershipError)")
3567 }
3568 return lines
3569 }
3570
3571 private static func exportSubdomainsLines(_ snapshot: LookupSnapshot) -> [String] {
3572 var lines: [String] = []
3573 lines.append(" Count: \(snapshot.subdomains.count)")
3574 if snapshot.subdomains.isEmpty {
3575 lines.append(" \(snapshot.subdomainsError ?? "No passive subdomains found")")
3576 } else {
3577 for subdomain in subdomainRows(from: snapshot) {
3578 let marker = subdomain.isInteresting ? " [interesting]" : ""
3579 lines.append(" \(subdomain.hostname)\(marker)")
3580 }
3581 }
3582 if !FeatureAccessService.hasAccess(to: .extendedSubdomains) {
3583 lines.append(" Extended subdomain discovery (Pro)")
3584 }
3585 return lines
3586 }
3587
3588 private static func exportDnsLines(_ snapshot: LookupSnapshot) -> [String] {
3589 var lines: [String] = []
3590 if let dnsError = snapshot.dnsError {
3591 lines.append(" Error: \(dnsError)")
3592 }
3593 if let dnssecLabel = dnssecLabel(from: snapshot) {
3594 lines.append(" \(dnssecLabel)")
3595 }
3596 for section in dnsRows(from: snapshot) {
3597 lines += exportDNSSectionLines(section)
3598 }
3599 if let ptrRecord = snapshot.ptrRecord {
3600 lines.append(" PTR: \(ptrRecord)")
3601 } else if let ptrError = snapshot.ptrError {
3602 lines.append(" PTR Error: \(ptrError)")
3603 }
3604 return lines
3605 }
3606
3607 private static func exportDNSSectionLines(_ section: DNSRecordSectionViewData) -> [String] {
3608 var lines = [" \(section.title)"]
3609 if let message = section.message {
3610 lines.append(" \(message.isError ? "Error" : "Info"): \(message.text)")
3611 }
3612 for row in section.rows {
3613 lines.append(" \(row.value) (\(row.label))")
3614 }
3615 if let wildcardTitle = section.wildcardTitle {
3616 lines.append(" \(wildcardTitle)")
3617 for row in section.wildcardRows {
3618 lines.append(" \(row.value) (\(row.label))")
3619 }
3620 }
3621 return lines
3622 }
3623
3624 private static func exportResponseLines(_ snapshot: LookupSnapshot) -> [String] {
3625 if let httpHeadersError = snapshot.httpHeadersError {
3626 return [" Headers Error: \(httpHeadersError)"]
3627 }
3628 var lines = webResponseRows(from: snapshot).map { " \($0.label): \($0.value)" }
3629 if snapshot.httpHeaders.isEmpty {
3630 lines.append(" Headers: No headers returned")
3631 } else {
3632 lines.append(" Headers:")
3633 for header in snapshot.httpHeaders {
3634 lines.append(" \(header.name): \(header.value)")
3635 }
3636 }
3637 return lines
3638 }
3639
3640 private static func exportWebLines(_ snapshot: LookupSnapshot) -> [String] {
3641 var lines: [String] = []
3642 if let sslError = snapshot.sslError {
3643 lines.append(" TLS Error: \(sslError)")
3644 } else {
3645 for row in webCertificateRows(from: snapshot) {
3646 lines.append(" \(row.label): \(row.value)")
3647 }
3648 }
3649 lines += exportResponseLines(snapshot)
3650
3651 if let redirectChainError = snapshot.redirectChainError {
3652 lines.append(" Redirect Error: \(redirectChainError)")
3653 } else if snapshot.redirectChain.isEmpty {
3654 lines.append(" Redirects: No redirect data available")
3655 } else {
3656 lines.append(" Redirects:")
3657 for hop in redirectRows(from: snapshot) {
3658 lines.append(" \(hop.stepLabel). \(hop.statusCode) \(hop.url)\(hop.isFinal ? " (final)" : "")")
3659 }
3660 }
3661 return lines
3662 }
3663
3664 private static func exportEmailLines(_ snapshot: LookupSnapshot) -> [String] {
3665 var lines: [String] = []
3666 if let emailSecurityError = snapshot.emailSecurityError {
3667 lines.append(" Error: \(emailSecurityError)")
3668 } else if emailRows(from: snapshot).isEmpty {
3669 lines.append(" No email security records found")
3670 } else {
3671 for row in emailRows(from: snapshot) {
3672 lines.append(" \(row.label): \(row.status)")
3673 lines.append(" \(row.detail)")
3674 if let auxiliaryDetail = row.auxiliaryDetail {
3675 lines.append(" \(auxiliaryDetail)")
3676 }
3677 }
3678 }
3679 return lines
3680 }
3681
3682 private static func exportPortLines(_ rows: [PortScanRowViewData]) -> [String] {
3683 guard !rows.isEmpty else { return [" No results"] }
3684 var lines: [String] = []
3685 for row in rows {
3686 lines.append(" \(row.portLabel) \(row.service): \(row.statusLabel)\(row.durationLabel.map { " \($0)" } ?? "")")
3687 if let banner = row.banner {
3688 lines.append(" Banner: \(banner)")
3689 }
3690 }
3691 return lines
3692 }
3693
3694 private static func exportNetworkLines(_ snapshot: LookupSnapshot) -> [String] {
3695 var lines: [String] = []
3696 if let reachabilityError = snapshot.reachabilityError {
3697 lines.append(" Reachability Error: \(reachabilityError)")
3698 } else if reachabilityRows(from: snapshot).isEmpty {
3699 lines.append(" Reachability: No results")
3700 } else {
3701 lines.append(" Reachability:")
3702 for row in reachabilityRows(from: snapshot) {
3703 lines.append(" \(row.portLabel): \(row.statusLabel) \(row.latencyLabel)")
3704 }
3705 }
3706
3707 if let ipGeolocationError = snapshot.ipGeolocationError, snapshot.ipGeolocation == nil {
3708 lines.append(" Location Error: \(ipGeolocationError)")
3709 } else if locationRows(from: snapshot).isEmpty {
3710 lines.append(" Location: No data")
3711 } else {
3712 lines.append(" Location:")
3713 for row in locationRows(from: snapshot) {
3714 lines.append(" \(row.label): \(row.value)")
3715 }
3716 }
3717
3718 if let portScanError = snapshot.portScanError, snapshot.portScanResults.isEmpty {
3719 lines.append(" Port Scan Error: \(portScanError)")
3720 }
3721
3722 lines.append(" Standard Ports:")
3723 lines += exportPortLines(portRows(from: snapshot, kind: .standard))
3724 lines.append(" Custom Ports:")
3725 lines += exportPortLines(portRows(from: snapshot, kind: .custom))
3726 return lines
3727 }
3728
3729 private static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
3382 static func primaryIPAddress(from snapshot: LookupSnapshot) -> String? {
37303383 snapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
37313384 }
37323385
3733 private static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
3386 static func finalRedirectTarget(from snapshot: LookupSnapshot) -> String? {
37343387 snapshot.redirectChain.last?.url
37353388 }
37363389
3737 private static func httpStatusGradeSummary(from snapshot: LookupSnapshot) -> String {
3738 let parts = [snapshot.httpStatusCode.map(String.init), snapshot.httpSecurityGrade].compactMap { $0 }
3739 if !parts.isEmpty {
3740 return parts.joined(separator: " / ")
3741 }
3742 return snapshot.httpHeadersError ?? "Unavailable"
3743 }
3744
3745 private static func httpsSummary(from snapshot: LookupSnapshot) -> String {
3390 static func httpsSummary(from snapshot: LookupSnapshot) -> String {
37463391 if snapshot.sslInfo != nil {
37473392 return "Valid"
37483393 }
@@ -3759,7 +3404,7 @@ final class DomainViewModel {
37593404 return snapshot.sslError == nil ? .secondary : .failure
37603405 }
37613406
3762 private static func emailSummary(from snapshot: LookupSnapshot) -> String {
3407 static func emailSummary(from snapshot: LookupSnapshot) -> String {
37633408 guard let emailSecurity = snapshot.emailSecurity else {
37643409 return snapshot.emailSecurityError ?? "Unavailable"
37653410 }
@@ -3803,7 +3448,7 @@ final class DomainViewModel {
38033448 return .success
38043449 }
38053450
3806 private static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
3451 static func availabilityLabel(_ status: DomainAvailabilityStatus?) -> String {
38073452 switch status {
38083453 case .available:
38093454 return "Available"
@@ -3866,7 +3511,7 @@ final class DomainViewModel {
38663511 }
38673512 }
38683513
3869 private static func durationLabel(_ durationMs: Int?) -> String {
3514 static func durationLabel(_ durationMs: Int?) -> String {
38703515 durationMs.map { "\($0) ms" } ?? "Unavailable"
38713516 }
38723517
@@ -3884,12 +3529,6 @@ final class DomainViewModel {
38843529 return formatter
38853530 }()
38863531
3887 private static let csvDateFormatter: ISO8601DateFormatter = {
3888 let formatter = ISO8601DateFormatter()
3889 formatter.formatOptions = [.withInternetDateTime]
3890 return formatter
3891 }()
3892
38933532 private func conciseExternalMessage(_ message: String, fallback: String) -> String {
38943533 let trimmed = message.trimmingCharacters(in: .whitespacesAndNewlines)
38953534 if trimmed.isEmpty {
@@ -3907,11 +3546,6 @@ final class DomainViewModel {
39073546 return trimmed
39083547 }
39093548
3910 private static func csvEscaped(_ value: String) -> String {
3911 let escaped = value.replacingOccurrences(of: "\"", with: "\"\"")
3912 return "\"\(escaped)\""
3913 }
3914
39153549 private static func isInterestingSubdomain(_ hostname: String) -> Bool {
39163550 let keywords = ["admin", "api", "dev", "staging", "test", "internal"]
39173551 let labels = hostname.lowercased().split(separator: ".").map(String.init)
@@ -3921,6 +3555,9 @@ final class DomainViewModel {
39213555 }
39223556}
39233557
3558// Private, and not shared with the identically named helpers elsewhere:
3559// DomainInsightEngine's `nilIfEmpty` trims whitespace first and these do not,
3560// so one internal version would quietly change behaviour there (A14).
39243561private extension String {
39253562 var nilIfEmpty: String? {
39263563 isEmpty ? nil : self