// The Swift face of the Rust core — the Mac's `CottonClient/CottonCore.swift`,// moved over and cut down to what a phone sends.//// An `actor` because the handle is not thread-safe by contract and every call// blocks the calling thread inside Rust — so it must never be the main one// (design P5, the Mac's M2). Anything long is a command that returns at once// and reports on the event stream: `join.start`, `bootstrap.start`, the sync// pass. The boot read and the Keychain read run off the main thread for the// same reason.//// **The seam is a protocol, not the actor.** Every model in this app takes// `any CottonCalling`, so a screen is testable without an XCFramework, without// a container and without a simulator's filesystem — which is the whole reason// `CottonUI` is a library target (P17). `FakeCore` below is the double every// test uses; `CottonCore` is the one implementation that touches C.#if canImport(CottonFFI)importCottonFFI#endifimportFoundation/// What the app hands the core at open — ONE shape for both destinations.////// The Rust side (`OpenConfig`, H1) reads the MODE off which keys are present:/// `containerPath` is a phone (the app group's container, Rust builds its whole/// layout under it); `home` is a host (a Mac that holds a database — the data/// directory's refusals and its one-time adoption run under `prepareDataDir`)./// Both at once, neither, or a host's field beside a container are refused by/// name, and a host config handed to the client build is refused at open —/// `no_server_in_this_build` — never at compile time. The JSON is/// `deny_unknown_fields` on the far side, and nothing here is/// optional-by-accident: a synthesised `Encodable` omits a nil optional, so an/// unset field is an absent field.////// Two constructors, so a call site reads as what it is: `CottonConfig(/// containerPath:)` is the phone's and `CottonConfig.host(...)` the Mac's, with/// the Mac's defaults (`NSHomeDirectory()`, `COTTON_MAC_DATA_DIR`, the bundle's/// version, the host name, "packaged" meaning a signed bundle).publicstructCottonConfig: Encodable, Sendable {/// WHICH APP this is — `real` or `dev`, the wire field `flavor`, on BOTH/// the phone's config and the Mac's. Read off this bundle's `CottonFlavor`/// stamp (`AppFlavor.current`, unstamped is dev) and handed down so the/// core decides the data folder, the port, the relay-name rule and the/// server it will talk to by the same word (`cotton-core/src/flavor.rs`)./// Never optional: a config that does not say which app it is would be/// read as Cotton Dev on the far side anyway, and saying so is honest.publicvar flavor: String = AppFlavor.current.rawValue/// WHICH BUSINESS APP this is, when it is one — the bundle's `flavour.json`/// (`FlavourManifest`), handed down unchanged so the core reads the same/// tools and database rule the screens do. Absent is Cotton.publicvar manifest: FlavourManifest? = FlavourManifest.current/// The phone: its data folder, in the app's own container/// (`PhoneDataDirectory`) — never the app group's.publicvar containerPath: String?/// The phone: the app group's container, where the data folder lived/// before 6 Oct 2026, so the core can rewrite the media rows' paths.publicvar previousContainerPath: String?/// The Mac: the home folder the data directory hangs off. Passed rather/// than read inside Rust so the data directory's rules stay pure and a/// test can point them at a synthetic folder.publicvar home: String?/// The Mac: `COTTON_MAC_DATA_DIR`, when set.publicvar dataDirOverride: String?publicvar appVersion: String?/// The Mac app identity for booked moves, independent of its device-row version.publicvar appBuildLabel: String?/// The Mac: whether to run the data directory's refusals and its one-time/// adoption. True in the app, always.publicvar prepareDataDir: Bool?/// The Mac: what this machine calls itself. Read here and passed down, so/// the rule that strips `.local` stays pure on the other side.publicvar hostname: String?/// This device's zone, read here and passed down, so the recurrence rules/// below the boundary stay pure. On the Mac it is read BEFORE anything/// pins the process to UTC.publicvar timeZone: String?/// The Mac: true inside a signed app bundle. It decides ONE thing — where/// the device seed lives — and it is false for `swift run` and for every/// test.publicvar packaged: Bool?/// The device seed, base64url, out of the Keychain (§3). Rust derives the/// id from it and signs every request with it; Swift never signs anything./// `nil` on an unpackaged Mac build, which keeps a rehearsal seed beside/// the synthetic database instead (design M8).publicvar deviceSecret: String?/// THE MAC'S VAULT KEY, base64url, out of the Keychain (spec §7.1).////// A HOST field, and the phone must never set it. The two devices hold the/// same kind of key and hold it completely differently: the Mac's is read/// once at open and kept for the process's life, because the server and the/// placement applier run unattended; the phone's is guarded by presence and/// crosses per call as `vault.unlock`'s parameter, so nothing holds it/// between two reveals. The core refuses a phone config that names one.publicvar vaultSecret: String?/// The phone's config.publicinit( containerPath: String, previousContainerPath: String? = nil, appVersion: String? = nil, timeZone: String? = TimeZone.current.identifier, deviceSecret: String? = nil ) {self.containerPath = containerPathself.previousContainerPath = previousContainerPathself.appVersion = appVersionself.timeZone = timeZoneself.deviceSecret = deviceSecret }privateinit() {}/// **The phone's version label** — "1.0.0 (248)": the marketing version/// and, in brackets, the build. The label rides every request onto the/// phone's synced device row (`app_version`), and the build in it is what/// the cutover tool's Mac-last gate reads (architect, 12 Oct 2026): the/// marketing version alone does not say which build a phone runs.publicstaticfunc versionLabel(short: String?, build: String?) -> String? {guardlet short, !short.isEmpty else { returnnil }guardlet build, !build.isEmpty else { return short }return"\(short) (\(build))" }/// This bundle's [`versionLabel`].publicstaticvar bundleVersionLabel: String? {let info = Bundle.main.infoDictionaryreturn versionLabel( short: info?["CFBundleShortVersionString"] as? String, build: info?["CFBundleVersion"] as? String ) }/// **The name a person reads on this machine's device row** — the Computer/// Name they gave it in System Settings ("Asha's iMac"), not/// `hostName`'s network spelling ("mac-a.local").////// The pairing list is read by a PERSON, and a row that names a machine has/// to name it the way they do (the Mac walk's walk-23, 2026-09-15)./// `hostName` stands in only where there is no localized name to read, and/// off macOS it is all there is.publicstaticvar machineName: String { #if os(macOS)returnHost.current().localizedName ?? ProcessInfo.processInfo.hostName #elsereturnProcessInfo.processInfo.hostName #endif }/// The Mac's config — a machine that holds a database.publicstaticfunc host( home: String = NSHomeDirectory(), dataDirOverride: String? = ProcessInfo.processInfo.environment["COTTON_MAC_DATA_DIR"], appVersion: String? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String, appBuildLabel: String? = CottonConfig.bundleVersionLabel, prepareDataDir: Bool = true, hostname: String? = CottonConfig.machineName, timeZone: String? = TimeZone.current.identifier, packaged: Bool = Bundle.main.bundleIdentifier != nil, deviceSecret: String? = nil, vaultSecret: String? = nil ) -> CottonConfig {var config = CottonConfig() config.home = home config.dataDirOverride = dataDirOverride config.appVersion = appVersion config.appBuildLabel = appBuildLabel config.prepareDataDir = prepareDataDir config.hostname = hostname config.timeZone = timeZone config.packaged = packaged config.deviceSecret = deviceSecret config.vaultSecret = vaultSecretreturn config }}/// Why the core would not open — a title and a message a screen can show/// unchanged.publicstructCottonRefusal: Error, Decodable, Equatable, Sendable {publiclet code: Stringpubliclet title: Stringpubliclet message: Stringpublicinit(code: String, title: String, message: String) {self.code = codeself.title = titleself.message = message }}/// Why a call did not answer. Its `message` is the core's sentence, and it is/// what `localizedDescription` draws: a screen that shows a caught error must/// never draw "(CottonKit.CottonCallError error 1.)" (walk6, Documents).publicstructCottonCallError: Error, Decodable, Equatable, Sendable, LocalizedError {publiclet code: Stringpubliclet message: Stringpubliclet details: JSONValue?publicinit(code: String, message: String, details: JSONValue? = nil) {self.code = codeself.message = messageself.details = details }publicvar errorDescription: String? {FlavourManifest.said(message.isEmpty ? "Cotton couldn't do that just now. Please try again." : message) }/// What a source that has no such method says: plain words, never the/// method's name (291 words row 6).publicstaticlet notOnThisDevice = "This device cannot do that."}/// An error on this side of the boundary: the core said something the app could/// not read.////// **It carries the raw answer and NEVER shows it.** The payload is for the/// log, for a report and for a test that wants to say what came back; the/// `errorDescription` is a sentence. Every screen's last-resort formatter is/// `String(describing:)` over whatever it caught, so an error that is not a/// `LocalizedError` is an error whose contents get drawn — and the walk of/// 15 Sep 2026 found the FFI's write envelope, JSON braces and all, written on/// the record sheet in red handwriting where the reason a recording had not/// been filed belonged.publicenumCottonClientError: Error, Equatable, LocalizedError {case malformedAnswer(String)publicvar errorDescription: String? {FlavourManifest.said("Cotton couldn't read what the core answered. Please try again.") }/// What actually came back, for the log and for a report. Never drawn.publicvar rawAnswer: String {switchself {case .malformedAnswer(let answer): return answer } }}/// One event off the stream. Ten kinds — `status data log client devices/// sharing analyze ingest tunnel backup` — buffered and replayed before/// subscribe, delivered with the lock released, from any thread.publicstructCottonEvent: Decodable, Equatable, Sendable {publiclet kind: Stringpubliclet payload: JSONValuepublicinit(kind: String, payload: JSONValue) {self.kind = kindself.payload = payload }}/// A request with no arguments. A struct with no stored properties encodes as/// `{}`, which is what the core reads an absent body as anyway.publicstructEmptyRequest: Encodable, Sendable {publicinit() {}}/// The core, as every model sees it.////// Four members and no fifth: ask, ask-and-decode, listen, close. Everything a/// screen wants is a method NAME inside `call`, which is the ABI's own rule/// carried one layer up — a fifth member here would be a second door into the/// same six C functions.publicprotocolCottonCalling: Sendable {/// The raw envelope, for a caller that wants the JSON itself.func callRaw(_ method: String, requestJSON: String) asyncthrows -> String/// Listen to the event stream. Everything buffered before now is replayed/// first, in order. ONE subscriber: a second call replaces the first.func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) asyncfunc close() async}extensionCottonCalling {/// Ask the core something, and decode its answer.publicfunc call<Response: Decodable>( _ method: String, _ request: someEncodable = EmptyRequest(),as _: Response.Type = Response.self ) asyncthrows -> Response {let body = String(decoding: try JSONEncoder().encode(request), as: UTF8.self)let answer = tryawait callRaw(method, requestJSON: body)let decoded: Answer<Response>do { decoded = try JSONDecoder().decode(Answer<Response>.self, from: Data(answer.utf8)) } catch {throwCottonClientError.malformedAnswer(answer) }iflet error = decoded.error { throw error }guardlet data = decoded.data else {throwCottonClientError.malformedAnswer(answer) }return data }/// The answer as an untyped tree, for a reader that is looking at one field/// of a shape the boundary owns.publicfunc callJSON( _ method: String, _ request: someEncodable = EmptyRequest() ) asyncthrows -> JSONValue {tryawait call(method, request, as: JSONValue.self) }}/// The envelope: `{"ok":true,"data":…}` / `{"ok":false,"error":{…}}`.privatestructAnswer<T: Decodable>: Decodable {let ok: Boollet data: T?let error: CottonCallError?}#if canImport(CottonFFI)/// The handle, and everything that must outlive the actor.////// **Why the pointer lives in a class rather than in the actor.** Closing is/// the one thing that has to happen from `deinit`, and under Swift 6's/// strict concurrency a nonisolated `deinit` may not touch actor-isolated/// state — `OpaquePointer` is not `Sendable`, so reading it there is a/// compile error rather than a race nobody notices. Putting the pointer,/// the subscription and the closed flag in one lock-guarded box makes the/// ownership explicit: the box is what holds the C resource, its `deinit`/// is what releases it, and the actor merely uses it.finalclassCoreHandle: @unchecked Sendable {let pointer: OpaquePointerprivatelet lock = NSLock()/// Calls run on this queue, CONCURRENTLY: the core below is its own/// locks (the replica's mutex, the client state's), and two calls in/// flight at once are what it was built for. `close` is the one/// barrier, so a call never enters a handle that is being closed.privatelet calls = DispatchQueue( label: "com.cottondb.core.calls", qos: .userInitiated, attributes: .concurrent )/// The quit's own lane: one SERIAL queue beside `calls`, for the calls a/// quit makes (`quitCall`). A serial queue gets a thread of its own even/// when the concurrent pool is spent — and on 12 Oct 2026 it was: a/// standby had 64 reads parked on `calls`, GCD's whole width, and a/// stop sent there would have waited for a thread that never came/// (standbyhang).privatelet quitLane = DispatchQueue( label: "com.cottondb.core.quit", qos: .userInitiated )/// Every box ever handed to C, kept alive — see `hold`.privatevar boxes: [Unmanaged<EventBox>] = []privatevar closed = falseinit(_ pointer: OpaquePointer) {self.pointer = pointer }/// Remember the subscription. ONE subscriber is the ABI's own rule, so/// a second `subscribe` replaces the first below the boundary and this/// only has to keep the object alive.////// **Nothing is ever released here, and that is deliberate.** The core/// delivers events with its lock RELEASED, from any thread — so at the/// moment `cotton_subscribe` swaps the context pointer, a callback may/// already be inside the trampoline holding the OLD box. Releasing it/// there is a use-after-free with no way to observe it from Swift. The/// cost of not releasing is one small object per `subscribe` call, and/// `subscribe` is called once per core; the cost of releasing is a/// crash nobody can reproduce.func hold(_ box: Unmanaged<EventBox>) { lock.lock()defer { lock.unlock() } boxes.append(box) }/// The queue class a task's priority maps to, so a hop off the/// cooperative pool keeps the priority the task was given.staticfunc qos(for priority: TaskPriority) -> DispatchQoS {let raw = priority.rawValuelet qosClass: DispatchQoS.QoSClass = raw >= TaskPriority.userInteractive.rawValue ? .userInteractive : raw >= TaskPriority.userInitiated.rawValue ? .userInitiated : raw >= TaskPriority.medium.rawValue ? .default : raw >= TaskPriority.utility.rawValue ? .utility : .backgroundreturnDispatchQoS(qosClass: qosClass, relativePriority: 0) }/// One call, off the calling thread, beside any other in flight.////// `cotton_call` is synchronous and takes as long as the method takes:/// a local read is milliseconds, and the owner-HTTP families — a share/// invitation, a push registration — are a round trip to the Mac with/// a 60 s ceiling. When every call queued on the actor above, a screen/// opened during one of those waited the whole round trip for a read/// the file could have answered at once. So the actor holds nothing/// while C runs: the work goes to the concurrent queue and the caller/// awaits its answer alone.func call(_ method: String, requestJSON: String) asyncthrows -> String { #if COTTON_DEVlet started = ContinuousClock.nowdefer { DevReads.note(method, started: started) } #endif// AT THE CALLER'S PRIORITY, not the queue's. An actor runs its// work at the priority of the task awaiting it; a plain queue hop// does not, and a screen's read dispatched at the queue's default// sat behind every other process on a busy Mac — measured at 2.5×// the actor's time under a load of ten (lane I5).let priority = Self.qos(for: Task.currentPriority)returntryawait run(method, requestJSON: requestJSON, on: calls, qos: priority) }/// One call a QUIT makes, on the quit's own lane rather than `calls` —/// see `quitLane`. Nothing else uses it: a read sent here would queue/// behind the server's drain.func quitCall(_ method: String, requestJSON: String) asyncthrows -> String {tryawait run(method, requestJSON: requestJSON, on: quitLane, qos: .userInitiated) }privatefunc run( _ method: String, requestJSON: String, on queue: DispatchQueue, qos priority: DispatchQoS ) asyncthrows -> String {tryawait withCheckedThrowingContinuation { continuation in queue.async(qos: priority) { [self] inCoreNativeThread.run(qos: priority) { [self] in// Read the flag on the queue that `close` barriers, so a// closed handle is never entered. lock.lock()let isClosed = closed lock.unlock()guard !isClosed else { continuation.resume(throwing: CottonClientError.malformedAnswer(""))return }let answer = method.withCString { methodPointer in requestJSON.withCString { requestPointer in cotton_call(pointer, methodPointer, requestPointer) } }guardlet answer else { continuation.resume(throwing: CottonClientError.malformedAnswer(""))return }defer { cotton_string_free(answer) } continuation.resume(returning: String(cString: answer)) } } } }/// Close, once. Idempotent, and safe from `deinit`.////// `cotton_subscribe(pointer, nil, nil)` stops new callbacks; one/// already running is why every held handler outlives this. `cotton_close` is the/// last thing, so nothing can be dispatched into a closed handle — and/// it runs as a BARRIER on the calls queue, so every call already in/// flight has returned before the pointer is freed, and none starts/// after.////// **And it is BOUNDED.** `cotton_close` is a synchronous C call, so/// this blocks whichever thread asked — and the thread that asks is/// usually one Swift concurrency lent out, a cooperative pool whose/// width is the machine's core count and which is built on the promise/// that nothing on it blocks. Park enough of them and no `await`/// anywhere in the process has a thread to resume on: `swift test` sat/// at 0 % CPU for 35 minutes on a shared CI runner, holding the/// machine-wide build lock, over exactly this/// (Cotton note "Repo landmines — why the build's rules exist"). Past the bound the handle is/// deliberately LEAKED and the caller gets its thread back, because a/// leaked core is a megabyte and a parked pool is the whole process./// The close below it is bounded too (`CottonHandle::close`), so the/// bound here is the second line and not the only one.func close() { lock.lock()guard !closed else { lock.unlock()return } closed = true lock.unlock()let finished = DispatchSemaphore(value: 0)// THE BLOCK NEVER HOLDS THE BOX — only what it needs: the pointer// and the quit lane. `deinit` calls this, and a block that captured// `self` held the box past its own `deinit` whenever it had not yet// been released when `deinit` returned — always after a timeout, and// in a race even after `finished.signal()`. Swift aborts on a freed// object something still holds ("deallocated with non-zero retain// count"): RouteTableTests crashed CottonTestHost so on one Mac on// 6, 8, 10, 12 and 14 Nov (verify-main #10190). The leak stays safe// without the box: the box never frees the pointer, `cotton_close`// in this block does, so a close that ran out of time returns and// the block closes the pointer later.let closing = ClosingPointer(raw: pointer)let quitLane = quitLane calls.async(flags: .barrier) {// A quit call still running holds the pointer too. quitLane.sync {}CoreNativeThread.run(qos: .userInitiated) { cotton_subscribe(closing.raw, nil, nil) cotton_close(closing.raw) } finished.signal() }if finished.wait(timeout: .now() + CottonRuntime.closeTimeout) == .timedOut {CottonRuntime.report(""" the core did not close within \(Int(CottonRuntime.closeTimeout)) s — \ leaving it to the operating system rather than waiting. The server log \ names the step that would not stop. """ ) } }deinit { close() } }/// The handle's pointer on its way to `cotton_close`, carried by a block/// that must not hold the handle (`CoreHandle.close`). Only that block/// reads it, after every call has returned.privatestructClosingPointer: @unchecked Sendable {let raw: OpaquePointer }/// The open core.public actor CottonCore: CottonCalling {privatelet handle: CoreHandle/// Open the core over an app-group container.////// Throws `CottonRefusal` when the container cannot be used — a/// sentence meant to be shown as written, not a code to map.publicstaticfuncopen(_ config: CottonConfig) throws -> CottonCore {tryCoreNativeThread.run(qos: .userInitiated) {Result { try openOnNativeThread(config) } }.get() }privatestaticfunc openOnNativeThread(_ config: CottonConfig) throws -> CottonCore {let json = String(decoding: try JSONEncoder().encode(config), as: UTF8.self)var errorText: UnsafeMutablePointer<CChar>?let handle = json.withCString { cotton_open($0, &errorText) }guardlet handle else {let refusal = errorText.map { pointer -> CottonRefusalindefer { cotton_string_free(pointer) }let text = String(cString: pointer)return (try? JSONDecoder().decode(CottonRefusal.self, from: Data(text.utf8))) ?? CottonRefusal( code: "unreadable", title: CottonCore.startFailureTitle, message: text ) }throw refusal ?? CottonRefusal( code: "unreadable", title: CottonCore.startFailureTitle, message: CottonCore.startFailureSilent ) }returnCottonCore(handle: CoreHandle(handle)) }privateinit(handle: CoreHandle) {self.handle = handle }/// The core's own version.public nonisolated staticvar version: String {guardlet text = cotton_version() else { return"" }defer { cotton_string_free(text) }returnString(cString: text) }/// Ask the core. NOT isolated to the actor: the call runs on the/// handle's concurrent queue beside any other, so a read is never/// queued behind a slow method — `CoreHandle.call` says why.public nonisolated func callRaw(_ method: String, requestJSON: String) asyncthrows -> String {tryawaitCallsInFlight.shared.during { tryawait handle.call(method, requestJSON: requestJSON) } }/// Listen. ONE subscriber: a second call replaces the first BELOW the/// boundary, and the order here is the whole safety of it — the new/// context is installed FIRST, and only then is the old one recorded as/// superseded. Handing C a pointer whose object had already been let go/// is the window this closes.publicfunc subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {CoreNativeThread.run(qos: .userInitiated) { [handle] inlet retained = Unmanaged.passRetained(EventBox(handler)) cotton_subscribe(handle.pointer, retained.toOpaque()) { context, line inguardlet context, let line else { return }let box = Unmanaged<EventBox>.fromOpaque(context).takeUnretainedValue()// The line is borrowed for the length of this call:// `String(cString:)` copies, and nothing here frees it.let text = String(cString: line)guardlet event = try? JSONDecoder().decode(CottonEvent.self, from: Data(text.utf8))else { return } box.handler(event) } handle.hold(retained) } }/// Close the core. Idempotent./// The quit: stop the server (it drains), then close — the call on the/// quit's own lane, so a calls queue full of parked reads cannot hold/// it. The caller bounds the whole of it/// (`QuitBudget`). `quit: true` begins the PROCESS's drain first, so/// no pass of this dying process starts (`cotton_server::drain`).publicfunc quit() async { _ = try? await handle.quitCall("server.stop", requestJSON: #"{"quit":true}"#) handle.close() }publicfunc close() { handle.close() }// The two sentences an open refusal falls back on. They are here rather// than in `CottonStrings` because `CottonKit` carries no string// catalogue — it is below the design system, not inside it — and these// two are the only prose in the module. `LanguageSweepTests` reads them// where they are.staticlet startFailureTitle = String(localized: "Cotton could not start")staticlet startFailureSilent = String( localized: "The core would not open and did not say why." ) }/// The class the C callback's context pointer points at.finalclassEventBox: @unchecked Sendable {let handler: @Sendable (CottonEvent) -> Voidinit(_ handler: @escaping @Sendable (CottonEvent) -> Void) {self.handler = handler } }#endif/// The one door into the core, whether or not the archive is present.////// It exists so no caller above `CottonKit` writes `#if canImport(CottonFFI)`./// The XCFramework is a gitignored BUILD PRODUCT — absent on a fresh clone and/// on any lane that has not run `scripts/build-xcframework.sh`, where/// `scripts/ffi-stub.sh`'s module-less placeholder holds the path instead so/// SwiftPM can still resolve the package. A placeholder carries no module, so/// `canImport(CottonFFI)` is false and this answers false. The app target does/// not link the binary directly, so a conditional written up there would be/// answering a question about a module it cannot see; asked here, it is/// answering about its own.publicenumCottonRuntime {/// How long a close waits before it goes on without the core.////// Outside the sum of the Rust side's own bounds — 25 s to stop the server/// and the replica, then 10 s for whatever is left on the blocking pool/// (`CottonHandle::close`) — on purpose. The inner deadline is the one that/// should fire and the one that can name the step that would not stop; this/// is the rung outside it, for the case where it did not fire at all: a/// blocking closure the operating system is holding, or a build whose core/// is older than this app.publicstaticlet closeTimeout: TimeInterval = 45/// Where a close that ran out of time says so. `stderr`, always: a wait/// that was abandoned must never be silent, and `CottonKit` is below the/// app's own logging.staticfunc report(_ text: String) {FileHandle.standardError.write(Data("cotton: \(text)\n".utf8)) }/// Whether this build has the core in it. `FFISmokeTests` FAILS rather than/// skipping when this is false, so "no XCFramework" is never a silent/// absence.publicstaticvar linksFFI: Bool { #if canImport(CottonFFI)returntrue #elsereturnfalse #endif }/// The core's own version, or the empty string when it is not linked.publicstaticvar version: String { #if canImport(CottonFFI)returnCottonCore.version #elsereturn"" #endif }/// The commit the linked core was built from, as its version carries it/// (`0.1.0+1a2b3c4d5`, `.dirty` when crates/ held edits): nine characters/// of the sha, or nil for an unstamped core. `scripts/core-fresh.sh`/// reads the same stamp out of the archive.publicstaticvar buildCommit: String? {guardlet plus = version.firstIndex(of: "+") else { returnnil }returnString(version[version.index(after: plus)...]) }/// Open the core over an app-group container.publicstaticfuncopen(_ config: CottonConfig) throws -> any CottonCalling { #if canImport(CottonFFI)returntryCottonCore.open(config) #elsethrowCottonRefusal( code: "no_ffi", title: "Cotton could not start", message:"The Rust core is not in this build. Run `bash scripts/build-xcframework.sh`." ) #endif }}