SPB Git

Repository Public

JSONSupport.swift 12.8 KB 322 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/JSONSupport.swift3// Description: JSON plumbing of the network layer: raw JSON carried as Data (note content and properties), the4//              tolerant date parser, the encoder/decoder used for every route, base64url.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Raw JSON1112/// A JSON value carried as its serialised bytes. This module does not interpret note documents: `content` and13/// `properties` travel as `RawJSON` and are parsed by `SPNotesDocument`.14///15/// When a `RawJSON` is decoded out of a larger answer its bytes are re-serialised canonically (sorted keys, no16/// escaped slashes); equality is semantic (key order and whitespace do not matter).17public struct RawJSON: Sendable, Codable, CustomStringConvertible {18    /// UTF-8 JSON text.19    public let data: Data2021    /// Wraps bytes that are already JSON (not validated here; an invalid payload fails when the request is encoded).22    public init(data: Data) { self.data = data }2324    /// Wraps JSON text.25    public init(string: String) { self.data = Data(string.utf8) }2627    /// Serialises an `Encodable` value.28    public init<T: Encodable>(encoding value: T) throws {29        self.data = try APIJSON.encoder().encode(value)30    }3132    /// `{}`33    public static let emptyObject = RawJSON(data: Data("{}".utf8))34    /// `null`35    public static let null = RawJSON(data: Data("null".utf8))3637    /// The JSON text.38    public var string: String { String(decoding: data, as: UTF8.self) }39    public var description: String { string }4041    /// Whether the bytes parse as JSON.42    public var isValid: Bool { (try? JSONValue(parsing: data)) != nil }4344    /// Decodes the payload into a typed value (dates follow the backend conventions).45    public func decode<T: Decodable>(_ type: T.Type = T.self) throws -> T {46        try APIJSON.decoder().decode(T.self, from: data)47    }4849    public init(from decoder: Decoder) throws {50        let value = try JSONValue(from: decoder)51        self.data = try APIJSON.encoder().encode(value)52    }5354    public func encode(to encoder: Encoder) throws {55        let value: JSONValue56        do { value = try JSONValue(parsing: data) } catch {57            throw EncodingError.invalidValue(self, .init(codingPath: encoder.codingPath, debugDescription: "RawJSON does not contain valid JSON"))58        }59        try value.encode(to: encoder)60    }61}6263extension RawJSON: Equatable {64    public static func == (lhs: RawJSON, rhs: RawJSON) -> Bool {65        if lhs.data == rhs.data { return true }66        guard let a = try? JSONValue(parsing: lhs.data), let b = try? JSONValue(parsing: rhs.data) else { return false }67        return a == b68    }69}7071/// Minimal JSON tree used to move arbitrary JSON through `Codable` (internal to the module).72enum JSONValue: Equatable, Sendable, Codable {73    case null74    case bool(Bool)75    case int(Int64)76    case double(Double)77    case string(String)78    case array([JSONValue])79    case object([String: JSONValue])8081    init(parsing data: Data) throws {82        self = try JSONDecoder().decode(JSONValue.self, from: data)83    }8485    init(from decoder: Decoder) throws {86        if let keyed = try? decoder.container(keyedBy: AnyKey.self) {87            var out: [String: JSONValue] = [:]88            out.reserveCapacity(keyed.allKeys.count)89            for key in keyed.allKeys { out[key.stringValue] = try keyed.decode(JSONValue.self, forKey: key) }90            self = .object(out)91            return92        }93        if var unkeyed = try? decoder.unkeyedContainer() {94            var out: [JSONValue] = []95            if let n = unkeyed.count { out.reserveCapacity(n) }96            while !unkeyed.isAtEnd { out.append(try unkeyed.decode(JSONValue.self)) }97            self = .array(out)98            return99        }100        let single = try decoder.singleValueContainer()101        if single.decodeNil() { self = .null }102        else if let b = try? single.decode(Bool.self) { self = .bool(b) }103        else if let i = try? single.decode(Int64.self) { self = .int(i) }104        else if let d = try? single.decode(Double.self) { self = .double(d) }105        else { self = .string(try single.decode(String.self)) }106    }107108    func encode(to encoder: Encoder) throws {109        switch self {110        case .null: var c = encoder.singleValueContainer(); try c.encodeNil()111        case .bool(let b): var c = encoder.singleValueContainer(); try c.encode(b)112        case .int(let i): var c = encoder.singleValueContainer(); try c.encode(i)113        case .double(let d): var c = encoder.singleValueContainer(); try c.encode(d)114        case .string(let s): var c = encoder.singleValueContainer(); try c.encode(s)115        case .array(let a):116            var c = encoder.unkeyedContainer()117            for v in a { try c.encode(v) }118        case .object(let o):119            var c = encoder.container(keyedBy: AnyKey.self)120            for (k, v) in o { try c.encode(v, forKey: AnyKey(k)) }121        }122    }123124    subscript(key: String) -> JSONValue? {125        if case .object(let o) = self { return o[key] }126        return nil127    }128    var stringValue: String? { if case .string(let s) = self { return s }; return nil }129    var boolValue: Bool? { if case .bool(let b) = self { return b }; return nil }130    var doubleValue: Double? {131        switch self {132        case .int(let i): return Double(i)133        case .double(let d): return d134        default: return nil135        }136    }137    var isNull: Bool { self == .null }138    func raw() -> RawJSON { RawJSON(data: (try? APIJSON.encoder().encode(self)) ?? Data("null".utf8)) }139}140141struct AnyKey: CodingKey {142    var stringValue: String143    var intValue: Int? { nil }144    init(_ string: String) { stringValue = string }145    init?(stringValue: String) { self.stringValue = stringValue }146    init?(intValue: Int) { return nil }147}148149// MARK: - Coders150151/// The JSON conventions of the backend.152public enum APIJSON {153    /// Decoder for server answers: ISO 8601 dates with or without fractional seconds (and the PostgreSQL text form154    /// `2026-11-18 14:08:56.283-05` that a few routes let through).155    public static func decoder() -> JSONDecoder {156        let d = JSONDecoder()157        d.dateDecodingStrategy = .custom { decoder in158            let c = try decoder.singleValueContainer()159            let text = try c.decode(String.self)160            guard let date = APIDate.parse(text) else {161                throw DecodingError.dataCorruptedError(in: c, debugDescription: "Unreadable date: \(text)")162            }163            return date164        }165        return d166    }167168    /// Encoder for request bodies: dates as ISO 8601 with milliseconds in UTC; keys sorted so that the same request169    /// always produces the same bytes (stable retries, testable bodies).170    public static func encoder() -> JSONEncoder {171        let e = JSONEncoder()172        e.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]173        e.dateEncodingStrategy = .custom { date, encoder in174            var c = encoder.singleValueContainer()175            try c.encode(APIDate.string(from: date))176        }177        return e178    }179}180181// MARK: - Dates182183/// Date parsing and formatting without `DateFormatter` (thread-safe, allocation-light).184public enum APIDate {185    /// Parses `YYYY-MM-DD[(T| )hh:mm[:ss[.fraction]]][Z|±hh[:mm]|±hhmm]`. A missing zone means UTC.186    public static func parse(_ text: String) -> Date? {187        let b = Array(text.utf8)188        var i = 0189        func digits(_ count: Int) -> Int? {190            guard i + count <= b.count else { return nil }191            var v = 0192            for k in 0..<count {193                let c = b[i + k]194                guard c >= 0x30, c <= 0x39 else { return nil }195                v = v * 10 + Int(c - 0x30)196            }197            i += count198            return v199        }200        func eat(_ c: UInt8) -> Bool {201            if i < b.count, b[i] == c { i += 1; return true }202            return false203        }204        guard let year = digits(4), eat(0x2D), let month = digits(2), eat(0x2D), let day = digits(2),205              (1...12).contains(month), (1...31).contains(day) else { return nil }206        var hour = 0, minute = 0, second = 0207        var fraction = 0.0208        var offset = 0209        if i < b.count {210            guard b[i] == 0x54 || b[i] == 0x74 || b[i] == 0x20 else { return nil }211            i += 1212            guard let h = digits(2), eat(0x3A), let m = digits(2), h <= 24, m <= 59 else { return nil }213            hour = h; minute = m214            if eat(0x3A) {215                guard let s = digits(2), s <= 60 else { return nil }216                second = s217                if eat(0x2E) || eat(0x2C) {218                    var scale = 0.1219                    var seen = false220                    while i < b.count, b[i] >= 0x30, b[i] <= 0x39 {221                        fraction += Double(b[i] - 0x30) * scale222                        scale /= 10223                        i += 1224                        seen = true225                    }226                    guard seen else { return nil }227                }228            }229            if eat(0x5A) || eat(0x7A) {230                offset = 0231            } else if i < b.count, b[i] == 0x2B || b[i] == 0x2D {232                let sign = b[i] == 0x2D ? -1 : 1233                i += 1234                guard let oh = digits(2), oh <= 23 else { return nil }235                var om = 0236                if i < b.count {237                    _ = eat(0x3A)238                    guard let m = digits(2), m <= 59 else { return nil }239                    om = m240                }241                offset = sign * (oh * 3600 + om * 60)242            }243            guard i == b.count else { return nil }244        }245        let days = daysFromCivil(year: year, month: month, day: day)246        let seconds = Double(days) * 86_400 + Double(hour * 3600 + minute * 60 + second - offset)247        // Round the fraction to the microsecond so that "….808Z" maps to exactly the same Date every time.248        return Date(timeIntervalSince1970: seconds + (fraction * 1_000_000).rounded() / 1_000_000)249    }250251    /// `2026-11-18T19:07:04.808Z` (UTC, milliseconds).252    public static func string(from date: Date) -> String {253        let totalMs = Int64((date.timeIntervalSince1970 * 1000).rounded())254        var seconds = totalMs / 1000255        var ms = totalMs % 1000256        if ms < 0 { ms += 1000; seconds -= 1 }257        var days = seconds / 86_400258        var rem = seconds % 86_400259        if rem < 0 { rem += 86_400; days -= 1 }260        let (y, m, d) = civilFromDays(Int(days))261        func pad(_ v: Int64, _ width: Int) -> String {262            let s = String(v)263            return String(repeating: "0", count: max(0, width - s.count)) + s264        }265        return "\(pad(Int64(y), 4))-\(pad(Int64(m), 2))-\(pad(Int64(d), 2))T\(pad(rem / 3600, 2)):\(pad(rem % 3600 / 60, 2)):\(pad(rem % 60, 2)).\(pad(ms, 3))Z"266    }267268    // Howard Hinnant's civil-date algorithms (proleptic Gregorian calendar).269    private static func daysFromCivil(year: Int, month: Int, day: Int) -> Int {270        let y = month <= 2 ? year - 1 : year271        let era = (y >= 0 ? y : y - 399) / 400272        let yoe = y - era * 400273        let doy = (153 * (month + (month > 2 ? -3 : 9)) + 2) / 5 + day - 1274        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy275        return era * 146_097 + doe - 719_468276    }277278    private static func civilFromDays(_ days: Int) -> (Int, Int, Int) {279        let z = days + 719_468280        let era = (z >= 0 ? z : z - 146_096) / 146_097281        let doe = z - era * 146_097282        let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365283        let y = yoe + era * 400284        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100)285        let mp = (5 * doy + 2) / 153286        let d = doy - (153 * mp + 2) / 5 + 1287        let m = mp < 10 ? mp + 3 : mp - 9288        return (m <= 2 ? y + 1 : y, m, d)289    }290}291292// MARK: - base64url293294/// base64url (RFC 4648 §5) as used by WebAuthn JSON.295public enum Base64URL {296    /// Encodes without padding.297    public static func encode(_ data: Data) -> String {298        data.base64EncodedString()299            .replacingOccurrences(of: "+", with: "-")300            .replacingOccurrences(of: "/", with: "_")301            .replacingOccurrences(of: "=", with: "")302    }303304    /// Decodes base64url or plain base64, with or without padding. Returns `nil` on any other character.305    public static func decode(_ text: String) -> Data? {306        var s = ""307        s.reserveCapacity(text.utf8.count + 3)308        for scalar in text.unicodeScalars {309            switch scalar {310            case "-": s.unicodeScalars.append("+")311            case "_": s.unicodeScalars.append("/")312            case "=": continue313            case "A"..."Z", "a"..."z", "0"..."9", "+", "/": s.unicodeScalars.append(scalar)314            default: return nil315            }316        }317        guard s.utf8.count % 4 != 1 else { return nil }318        s += String(repeating: "=", count: (4 - s.utf8.count % 4) % 4)319        return Data(base64Encoded: s)320    }321}322
Files main
Menu

Theme