Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Infrastructure/package-builder/Tests/PackageBuilderKitTests/BuilderTests.swift10// Module : PackageBuilderKitTests11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import Foundation90import ORIXGeoCore91import ORIXMapPackage92import Testing93@testable import PackageBuilderKit9495final class Scratch: @unchecked Sendable {96 let url: URL97 init() {98 url = FileManager.default.temporaryDirectory.appendingPathComponent("orix-builder-\(UUID().uuidString)")99 try! FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)100 }101 deinit { try? FileManager.default.removeItem(at: url) }102 func path(_ name: String) -> String { url.appendingPathComponent(name).path }103 func file(_ name: String) -> URL { url.appendingPathComponent(name) }104}105106/// Runs the command in-process and captures what it prints.107func tool(_ arguments: String..., environment: [String: String] = [:]) async -> (status: Int32, out: String, err: String) {108 final class Sink: @unchecked Sendable { var out: [String] = []; var err: [String] = [] }109 let sink = Sink()110 let status = await CommandLineTool.run(arguments: arguments, environment: environment, output: { sink.out.append($0) }, errorOutput: { sink.err.append($0) })111 return (status, sink.out.joined(separator: "\n"), sink.err.joined(separator: "\n"))112}113114let montreal = BoundingBox(minLat: 45.15, minLon: -74.35, maxLat: 45.95, maxLon: -73.15)115116@Suite struct PMTilesHeaderTests {117 let scratch = Scratch()118119 @Test func readsZoomAndBoundsOfAValidArchive() throws {120 let url = scratch.file("a.pmtiles")121 try Fixtures.writePMTiles(to: url, size: 50_000, bounds: montreal, minZoom: 2, maxZoom: 14)122 #expect(try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int == 50_000)123 let h = try PMTilesHeader.read(url)124 #expect(h.minZoom == 2 && h.maxZoom == 14)125 #expect(h.tileType == .mvt)126 #expect(h.bounds == montreal)127 #expect(h.rootDirectoryOffset == 127 && h.rootDirectoryLength == 1)128 #expect(h.tileDataOffset + h.tileDataLength == 50_000)129 #expect(try PMTilesHeader.parse(h.encoded()) == h)130 #expect(h.encoded().count == 127)131 }132133 @Test func rejectsEverythingElse() throws {134 let url = scratch.file("a.pmtiles")135 try Fixtures.writePMTiles(to: url, size: 5000, bounds: montreal)136 let good = try Data(contentsOf: url)137 func parse(_ edit: (inout Data) -> Void, size: UInt64? = 5000) -> PMTilesHeader.ParseError? {138 var d = good; edit(&d)139 do { _ = try PMTilesHeader.parse(d, fileSize: size); return nil } catch { return error }140 }141 func put64(_ d: inout Data, _ v: UInt64, _ o: Int) { for i in 0..<8 { d[o + i] = UInt8(truncatingIfNeeded: v >> (8 * UInt64(i))) } }142 #expect(parse { _ in } == nil)143 #expect(parse { $0 = $0.prefix(126) } == .tooShort(length: 126))144 #expect(parse { $0 = Data() } == .tooShort(length: 0))145 #expect(parse { $0[0] = 0x51 } == .badMagic)146 #expect(parse { $0.replaceSubrange(0..<7, with: Array("SQLite ".utf8)) } == .badMagic)147 #expect(parse { $0[7] = 2 } == .unsupportedVersion(2))148 #expect(parse { $0[7] = 4 } == .unsupportedVersion(4))149 #expect(parse { $0[100] = 15 } == .invalidZoomRange(min: 15, max: 14))150 #expect(parse { $0[101] = 31 } == .invalidZoomRange(min: 0, max: 31))151 #expect(parse { put64(&$0, 0, 16) } == .missingRootDirectory)152 #expect(parse { put64(&$0, 10, 8) } == .missingRootDirectory)153 #expect(parse { put64(&$0, 6000, 8) } == .sectionOutOfFile("root directory"))154 #expect(parse { put64(&$0, UInt64.max, 32) } == .sectionOutOfFile("metadata"))155 #expect(parse { put64(&$0, UInt64.max - 1, 40); put64(&$0, 2, 48) } == .sectionOutOfFile("leaf directories"))156 #expect(parse { put64(&$0, 4871, 64) } == .sectionOutOfFile("tile data"))157 #expect(parse({ _ in }, size: 4999) == .sectionOutOfFile("tile data"))158 // Bounds that make no sense are reported as unknown, not invented.159 var h = try PMTilesHeader.parse(good)160 h.minLatE7 = 910_000_000161 #expect(h.bounds == nil)162 h = try PMTilesHeader.parse(good); h.maxLonE7 = h.minLonE7163 #expect(h.bounds == nil)164 #expect(throws: PMTilesHeader.ParseError.self) { try PMTilesHeader.read(self.scratch.file("missing.pmtiles")) }165 }166167 @Test func randomBytesNeverCrashTheParser() {168 var state: UInt64 = 0x1234_5678_9ABC_DEF1169 func next() -> UInt64 { state ^= state << 13; state ^= state >> 7; state ^= state << 17; return state }170 for i in 0..<20_000 {171 var bytes = (0..<Int(next() % 200)).map { _ in UInt8(truncatingIfNeeded: next()) }172 if i % 2 == 0, bytes.count >= 8 { bytes.replaceSubrange(0..<8, with: Array("PMTiles".utf8) + [3]) }173 _ = try? PMTilesHeader.parse(Data(bytes), fileSize: next() % 100_000)174 }175 }176}177178@Suite struct SigningKeyTests {179 let scratch = Scratch()180181 @Test func keygenWritesAPrivateKeyOnlyItsOwnerCanRead() throws {182 let dir = scratch.file("signing")183 let g = try SigningKeys.generate(in: dir, label: "test")184 let mode = try #require(try FileManager.default.attributesOfItem(atPath: g.privateKeyURL.path)[.posixPermissions] as? Int)185 #expect(mode == 0o600)186 #expect(try FileManager.default.attributesOfItem(atPath: dir.path)[.posixPermissions] as? Int == 0o700)187 #expect(g.privateKeyURL.lastPathComponent == "orixmap-\(g.keyId).key")188 let key = try SigningKeys.loadPrivateKey(at: g.privateKeyURL)189 #expect(TrustedKey(key.publicKey).keyId == g.keyId)190 #expect(try SigningKeys.loadTrust(at: g.trustStoreURL).keys.map(\.keyId) == [g.keyId])191 #expect(try SigningKeys.loadTrust(at: g.publicKeyURL).keys.map(\.keyId) == [g.keyId])192 #expect(try SigningKeys.loadTrust(at: g.trustStoreURL).keys[0].label == "test")193 // The public files do not contain the private key.194 let secret = try String(contentsOf: g.privateKeyURL, encoding: .utf8).trimmingCharacters(in: .whitespacesAndNewlines)195 for url in [g.publicKeyURL, g.trustStoreURL] { #expect(!(try String(contentsOf: url, encoding: .utf8)).contains(secret)) }196 #expect(SigningKeys.swiftSnippet(keyId: g.keyId, publicKeyBase64: g.publicKeyBase64, label: "test").contains(g.publicKeyBase64))197 }198199 @Test func loosePermissionsLinksAndGarbageAreRefused() throws {200 let g = try SigningKeys.generate(in: scratch.file("signing"), label: nil)201 func load(_ url: URL) -> SigningKeys.KeyError? { do { _ = try SigningKeys.loadPrivateKey(at: url); return nil } catch { return error } }202 #expect(load(g.privateKeyURL) == nil)203 for mode in [0o644, 0o640, 0o604, 0o660, 0o601] {204 try FileManager.default.setAttributes([.posixPermissions: mode], ofItemAtPath: g.privateKeyURL.path)205 #expect(load(g.privateKeyURL) == .loosePermissions(path: g.privateKeyURL.path, mode: String(mode, radix: 8)))206 }207 try FileManager.default.setAttributes([.posixPermissions: 0o400], ofItemAtPath: g.privateKeyURL.path)208 #expect(load(g.privateKeyURL) == nil, "read-only for the owner is fine")209 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: g.privateKeyURL.path)210211 let link = scratch.file("link.key")212 try FileManager.default.createSymbolicLink(at: link, withDestinationURL: g.privateKeyURL)213 #expect(load(link) == .notARegularFile(link.path))214 #expect(load(scratch.file("signing")) == .notARegularFile(scratch.path("signing")))215 #expect(load(scratch.file("nothing.key")) == .missing(scratch.path("nothing.key")))216 let garbage = scratch.file("garbage.key")217 FileManager.default.createFile(atPath: garbage.path, contents: Data("not a key".utf8), attributes: [.posixPermissions: 0o600])218 #expect(load(garbage) == .malformed(garbage.path))219 let short = scratch.file("short.key")220 FileManager.default.createFile(atPath: short.path, contents: Data(Data(count: 16).base64EncodedString().utf8), attributes: [.posixPermissions: 0o600])221 #expect(load(short) == .malformed(short.path))222 #expect(throws: SigningKeys.KeyError.malformed(garbage.path)) { try SigningKeys.loadTrust(at: garbage) }223 }224}225226@Suite struct CommandLineTests {227 let scratch = Scratch()228229 /// keygen + synthetic components; returns the key id.230 func prepare() async throws -> String {231 let keygen = await tool("keygen", "--out", scratch.path("keys"), "--label", "unit test")232 #expect(keygen.status == 0)233 let keyId = try #require(try FileManager.default.contentsOfDirectory(atPath: scratch.path("keys")).first { $0.hasSuffix(".key") })234 .replacingOccurrences(of: "orixmap-", with: "").replacingOccurrences(of: ".key", with: "")235 #expect(keygen.out.contains(keyId))236 #expect(keygen.out.contains("TrustedKey(publicKey: Data(base64Encoded:"))237 #expect((await tool("fixture", "--kind", "pmtiles", "--size", "300000", "--out", scratch.path("map.pmtiles"))).status == 0)238 #expect((await tool("fixture", "--kind", "blob", "--size", "120000", "--out", scratch.path("search.sqlite"), "--seed", "2")).status == 0)239 #expect((await tool("fixture", "--kind", "blob", "--size", "80000", "--out", scratch.path("routing.orixgraph"), "--seed", "3")).status == 0)240 try Data(#"[{"source":"OpenStreetMap","licence":"ODbL-1.0","attribution":"© OpenStreetMap contributors","url":"https://www.openstreetmap.org/copyright"}]"#.utf8)241 .write(to: scratch.file("licences.json"))242 return keyId243 }244245 func build(_ keyId: String, version: String, region: String = "ca-qc-montreal", out: String? = nil, extra: [String] = []) async -> (status: Int32, out: String, err: String) {246 let arguments = ["build", "--region", region, "--name-en", "Greater Montréal", "--name-fr", "Grand Montréal", "--data-version", version,247 "--data-timestamp", "2026-11-24T00:00:00Z", "--map", scratch.path("map.pmtiles"), "--search", scratch.path("search.sqlite"),248 "--routing", scratch.path("routing.orixgraph"), "--licences", scratch.path("licences.json"),249 "--key", scratch.path("keys/orixmap-\(keyId).key"), "--out", out ?? scratch.path("\(region)-\(version).orixmap")] + extra250 final class Sink: @unchecked Sendable { var out: [String] = []; var err: [String] = [] }251 let sink = Sink()252 let status = await CommandLineTool.run(arguments: arguments, environment: [:], output: { sink.out.append($0) }, errorOutput: { sink.err.append($0) })253 return (status, sink.out.joined(separator: "\n"), sink.err.joined(separator: "\n"))254 }255256 @Test func buildVerifyInspectInstall() async throws {257 let keyId = try await prepare()258 let trust = scratch.path("keys/orixmap-\(keyId).trust.json")259 let package = scratch.path("ca-qc-montreal-2026.11.24.orixmap")260 let built = await build(keyId, version: "2026.11.24", extra: ["--builder", "tile-builder=0.3.1", "--min-app-version", "1.0", "--name", "es=Gran Montreal"])261 #expect(built.status == 0, "\(built.err)")262263 // The manifest carries what the PMTiles header says.264 let manifest = try PackageVerifier(trustStore: try SigningKeys.loadTrust(at: URL(fileURLWithPath: trust))).verify(at: URL(fileURLWithPath: package)).manifest265 #expect(manifest.mapZoom == ZoomRange(minZoom: 0, maxZoom: 14))266 #expect(manifest.bbox == montreal, "bounds read from the PMTiles header")267 #expect(manifest.capabilities == ["map", "search", "routing"])268 #expect(manifest.builder == ["orix-package": CommandLineTool.version, "tile-builder": "0.3.1"])269 #expect(manifest.names["es"] == "Gran Montreal")270 #expect(manifest.signingKeyId == keyId)271 #expect(manifest.installedSize == 500_000)272273 let verified = await tool("verify", package, "--trust", trust)274 #expect(verified.status == 0 && verified.out.hasPrefix("OK "))275 #expect((await tool("verify", package, "--trust", scratch.path("keys/orixmap-\(keyId).pub"))).status == 0, "a bare public key works as trust")276277 let inspected = await tool("inspect", package, "--trust", trust)278 #expect(inspected.status == 0)279 for expected in ["orixmap 1.0", "ca-qc-montreal", "signature valid, key trusted", "layout valid", "map.pmtiles", "search.sqlite", "routing.orixgraph", "ODbL-1.0", keyId] {280 #expect(inspected.out.contains(expected), "inspect output lacks \(expected)")281 }282 let json = await tool("inspect", package, "--json")283 #expect(try PackageManifest.decode(Data(json.out.utf8)) == manifest)284285 // Tampering and foreign keys.286 var bytes = try Data(contentsOf: URL(fileURLWithPath: package))287 bytes[bytes.count - 5] ^= 1288 try bytes.write(to: scratch.file("tampered.orixmap"))289 let tampered = await tool("verify", scratch.path("tampered.orixmap"), "--trust", trust)290 #expect(tampered.status == 1 && tampered.err.contains("componentChecksumMismatch"))291 _ = await tool("keygen", "--out", scratch.path("other-keys"))292 let otherTrust = try #require(try FileManager.default.contentsOfDirectory(atPath: scratch.path("other-keys")).first { $0.hasSuffix(".trust.json") })293 let foreign = await tool("verify", package, "--trust", scratch.path("other-keys/\(otherTrust)"))294 #expect(foreign.status == 1 && foreign.err.contains("unknownSigningKey"))295 #expect((await tool("inspect", package, "--trust", scratch.path("other-keys/\(otherTrust)"))).out.contains("REJECTED"))296297 // What the phone does, on this Mac.298 let installed = await tool("install", package, "--store", scratch.path("store"), "--trust", trust)299 #expect(installed.status == 0, "\(installed.err)")300 #expect(FileManager.default.fileExists(atPath: scratch.path("store/regions/ca-qc-montreal/2026.11.24/map.pmtiles")))301 #expect(try Data(contentsOf: scratch.file("store/regions/ca-qc-montreal/2026.11.24/map.pmtiles")) == Data(contentsOf: scratch.file("map.pmtiles")))302 #expect((await tool("install", package, "--store", scratch.path("store"), "--trust", trust)).err.contains("alreadyInstalled"))303 }304305 @Test func buildRefusesBadInputAndLooseKeys() async throws {306 let keyId = try await prepare()307 let keyPath = scratch.path("keys/orixmap-\(keyId).key")308 // The key from the environment variable.309 let viaEnvironment = await tool("build", "--region", "ca-qc-montreal", "--name-en", "A", "--name-fr", "B", "--data-version", "1", "--data-timestamp", "2026-11-24T00:00:00Z",310 "--map", scratch.path("map.pmtiles"), "--licences", scratch.path("licences.json"), "--out", scratch.path("env.orixmap"),311 environment: [SigningKeys.environmentVariable: keyPath])312 #expect(viaEnvironment.status == 0, "\(viaEnvironment.err)")313 #expect((await build(keyId, version: "1", extra: [])).status == 0)314315 try FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: keyPath)316 let loose = await build(keyId, version: "2")317 #expect(loose.status == 1 && loose.err.contains("chmod 600"))318 #expect(!FileManager.default.fileExists(atPath: scratch.path("ca-qc-montreal-2.orixmap")))319 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: keyPath)320321 #expect((await build(keyId, version: "2026-11-24")).err.contains("--data-version"))322 #expect((await build(keyId, version: "3", region: "../evil", out: scratch.path("evil.orixmap"))).err.contains("invalidRegionId"))323 #expect((await build(keyId, version: "3", extra: ["--bbox", "1,2,3"])).err.contains("--bbox"))324 #expect((await build(keyId, version: "3", extra: ["--bbox", "-74,46,-73,45"])).err.contains("invalidBoundingBox"))325 #expect((await build(keyId, version: "3", extra: ["--unknown-option", "x"])).err.contains("unknown option"))326 #expect((await build(keyId, version: "3", extra: ["--terrain", scratch.path("search.sqlite")])).err.contains("not a valid PMTiles"))327 // A map that is not PMTiles.328 try FileManager.default.copyItem(at: scratch.file("search.sqlite"), to: scratch.file("fake.pmtiles"))329 let notPMTiles = await tool("build", "--region", "x", "--name-en", "A", "--name-fr", "B", "--data-version", "1", "--data-timestamp", "2026-11-24T00:00:00Z",330 "--map", scratch.path("fake.pmtiles"), "--licences", scratch.path("licences.json"), "--key", keyPath, "--out", scratch.path("x.orixmap"))331 #expect(notPMTiles.status == 1 && notPMTiles.err.contains("badMagic"))332 let noKey = await tool("build", "--region", "x", "--name-en", "A", "--name-fr", "B", "--data-version", "1", "--data-timestamp", "2026-11-24T00:00:00Z",333 "--map", scratch.path("map.pmtiles"), "--licences", scratch.path("licences.json"), "--out", scratch.path("x.orixmap"))334 #expect(noKey.status == 1 && noKey.err.contains("no signing key"))335 #expect((await tool("frobnicate")).status == 2)336 #expect((await tool()).status == 2)337 #expect((await tool("--help")).status == 0)338 #expect(try FileManager.default.contentsOfDirectory(atPath: scratch.url.path).allSatisfy { !$0.contains(".tmp-") })339 }340341 @Test func publishCatalogAndRollback() async throws {342 let keyId = try await prepare()343 let trust = scratch.path("keys/orixmap-\(keyId).trust.json")344 let dist = scratch.path("dist")345 #expect((await build(keyId, version: "2026.11.10")).status == 0)346 #expect((await build(keyId, version: "2026.11.24")).status == 0)347 #expect((await build(keyId, version: "2026.11.24", region: "ca-qc-quebec")).status == 0)348349 var result = await tool("publish", scratch.path("ca-qc-montreal-2026.11.10.orixmap"), "--dir", dist, "--trust", trust)350 #expect(result.status == 0, "\(result.err)")351 result = await tool("publish", scratch.path("ca-qc-montreal-2026.11.24.orixmap"), "--dir", dist, "--trust", trust)352 #expect(result.status == 0, "\(result.err)")353 result = await tool("publish", scratch.path("ca-qc-quebec-2026.11.24.orixmap"), "--dir", dist, "--trust", trust)354 #expect(result.status == 0, "\(result.err)")355356 func catalog() throws -> Catalog { try Catalog.decode(try Data(contentsOf: scratch.file("dist/catalog.json"))) }357 func versions(_ id: String) throws -> CatalogRegionVersions { try CatalogRegionVersions.decode(try Data(contentsOf: scratch.file("dist/regions/\(id)/versions.json"))) }358 var c = try catalog()359 #expect(c.regions.map(\.id) == ["ca-qc-montreal", "ca-qc-quebec"])360 #expect(c.skippedRegions == 0)361 let montrealEntry = try #require(c.region("ca-qc-montreal"))362 #expect(montrealEntry.latest.dataVersion == DataVersion("2026.11.24"))363 #expect(montrealEntry.latest.path == "files/ca-qc-montreal/2026.11.24/ca-qc-montreal-2026.11.24.orixmap")364 // Every artefact the catalog references exists, with the announced size and digest.365 for region in c.regions {366 let file = scratch.file("dist/\(region.latest.path)")367 let data = try Data(contentsOf: file)368 #expect(UInt64(data.count) == region.latest.downloadSize)369 #expect(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() == region.latest.sha256)370 #expect(region.latest.signingKeyId == keyId)371 #expect(try PackageHeader.parse(data).preambleLength == region.latest.preambleSize)372 }373 #expect(try versions("ca-qc-montreal").versions.map(\.dataVersion) == [DataVersion("2026.11.24")!, DataVersion("2026.11.10")!])374 let detail = try CatalogRegionDetail.decode(try Data(contentsOf: scratch.file("dist/regions/ca-qc-montreal.json")))375 #expect(detail.region == montrealEntry)376 #expect(detail.components.map(\.id) == ["map", "search", "routing"])377 #expect(detail.licences.first?.licence == "ODbL-1.0")378379 // Rollback: one command points "latest" back; the newer version stays listed.380 result = await tool("catalog", "--dir", dist, "--trust", trust, "--latest", "ca-qc-montreal=2026.11.10", "--generated-at", "2026-11-26T00:00:00Z")381 #expect(result.status == 0 && result.out.contains("latest 2026.11.10 (pinned)"), "\(result.err)")382 c = try catalog()383 #expect(c.generatedAt == "2026-11-26T00:00:00Z")384 #expect(c.region("ca-qc-montreal")?.latest.dataVersion == DataVersion("2026.11.10"))385 #expect(try versions("ca-qc-montreal").latest == DataVersion("2026.11.10"))386 #expect(try versions("ca-qc-montreal").versions.count == 2)387 // The pin survives a plain regeneration, and is removed on request.388 #expect((await tool("catalog", "--dir", dist, "--trust", trust)).status == 0)389 #expect(try catalog().region("ca-qc-montreal")?.latest.dataVersion == DataVersion("2026.11.10"))390 #expect((await tool("catalog", "--dir", dist, "--trust", trust, "--unpin", "ca-qc-montreal")).status == 0)391 #expect(try catalog().region("ca-qc-montreal")?.latest.dataVersion == DataVersion("2026.11.24"))392 #expect(!FileManager.default.fileExists(atPath: scratch.path("dist/pins.json")))393 #expect((await tool("catalog", "--dir", dist, "--trust", trust, "--latest", "ca-qc-montreal=1999.1.1")).err.contains("no published version"))394395 // A corrupted or misplaced artefact blocks the publication and leaves the catalog as it was.396 let before = try Data(contentsOf: scratch.file("dist/catalog.json"))397 let artefact = scratch.file("dist/files/ca-qc-quebec/2026.11.24/ca-qc-quebec-2026.11.24.orixmap")398 let original = try Data(contentsOf: artefact)399 var corrupted = original; corrupted[corrupted.count - 1] ^= 1400 try corrupted.write(to: artefact)401 result = await tool("catalog", "--dir", dist, "--trust", trust)402 #expect(result.status == 1 && result.err.contains("invalid package files/ca-qc-quebec"))403 #expect(try Data(contentsOf: scratch.file("dist/catalog.json")) == before)404 try original.write(to: artefact)405 try FileManager.default.createDirectory(at: scratch.file("dist/files/ca-on-ottawa/2026.11.24"), withIntermediateDirectories: true)406 try original.write(to: scratch.file("dist/files/ca-on-ottawa/2026.11.24/ca-on-ottawa-2026.11.24.orixmap"))407 result = await tool("catalog", "--dir", dist, "--trust", trust)408 #expect(result.status == 1 && result.err.contains("wrong directory"))409 try FileManager.default.removeItem(at: scratch.file("dist/files/ca-on-ottawa"))410 try Data("x".utf8).write(to: scratch.file("dist/files/ca-qc-quebec/2026.11.24/stray.txt"))411 #expect((await tool("catalog", "--dir", dist, "--trust", trust)).err.contains("unexpected entry"))412 try FileManager.default.removeItem(at: scratch.file("dist/files/ca-qc-quebec/2026.11.24/stray.txt"))413 #expect(try Data(contentsOf: scratch.file("dist/catalog.json")) == before)414415 // Withdrawing a region: its documents disappear after the catalog stops listing it.416 try FileManager.default.removeItem(at: scratch.file("dist/files/ca-qc-quebec"))417 result = await tool("catalog", "--dir", dist, "--trust", trust)418 #expect(result.status == 0 && result.out.contains("removed regions/ca-qc-quebec.json"))419 #expect(try catalog().regions.map(\.id) == ["ca-qc-montreal"])420 #expect(!FileManager.default.fileExists(atPath: scratch.path("dist/regions/ca-qc-quebec")))421 #expect(try FileManager.default.subpathsOfDirectory(atPath: dist).allSatisfy { !$0.contains(".incoming-") && !$0.contains(".tmp") })422 #expect((await tool("catalog", "--dir", scratch.path("nowhere"), "--trust", trust)).err.contains("no files/ directory"))423 }424}425