SPB Git

Repository Public License

JSONValue.swift 5.5 KB 126 lines swift

1import Foundation23/// A JSON tree. Used for request bodies, tool parameter schemas, tool-call arguments and opaque provider state.4public enum JSONValue: Sendable, Hashable, Codable {5    case null6    case bool(Bool)7    case number(Double)8    case string(String)9    case array([JSONValue])10    case object([String: JSONValue])1112    // MARK: Access1314    public subscript(key: String) -> JSONValue? {15        if case .object(let fields) = self { return fields[key] }16        return nil17    }1819    public subscript(index: Int) -> JSONValue? {20        if case .array(let items) = self, items.indices.contains(index) { return items[index] }21        return nil22    }2324    public var stringValue: String? { if case .string(let value) = self { return value }; return nil }25    public var boolValue: Bool? { if case .bool(let value) = self { return value }; return nil }26    public var arrayValue: [JSONValue]? { if case .array(let value) = self { return value }; return nil }27    public var objectValue: [String: JSONValue]? { if case .object(let value) = self { return value }; return nil }28    public var isNull: Bool { self == .null }2930    /// A number, or a numeric string (OpenRouter publishes prices as strings).31    public var doubleValue: Double? {32        switch self {33        case .number(let value): return value34        case .string(let text): return Double(text)35        default: return nil36        }37    }3839    /// An integral number. Fractions and values outside `Int` are not integers.40    public var intValue: Int? {41        guard case .number(let value) = self, value.isFinite, value == value.rounded(), abs(value) < 9.0e15 else { return nil }42        return Int(value)43    }4445    // MARK: Parsing and serialisation4647    public static func parse(_ data: Data) -> JSONValue? {48        guard let object = try? JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed]) else { return nil }49        return JSONValue(any: object)50    }5152    public static func parse(_ text: String) -> JSONValue? { parse(Data(text.utf8)) }5354    /// Compact JSON with sorted keys, so the same value always produces the same bytes (stable request bodies help55    /// provider-side prompt caches and make tests deterministic).56    public var data: Data {57        (try? JSONSerialization.data(withJSONObject: any, options: [.sortedKeys, .fragmentsAllowed, .withoutEscapingSlashes])) ?? Data("null".utf8)58    }5960    public func serialized() -> String { String(decoding: data, as: UTF8.self) }6162    init?(any: Any) {63        switch any {64        case is NSNull: self = .null65        case let number as NSNumber:66            // JSONSerialization represents booleans as the CFBoolean singletons.67            if CFGetTypeID(number) == CFBooleanGetTypeID() { self = .bool(number.boolValue) } else { self = .number(number.doubleValue) }68        case let text as String: self = .string(text)69        case let items as [Any]: self = .array(items.compactMap(JSONValue.init(any:)))70        case let fields as [String: Any]: self = .object(fields.compactMapValues(JSONValue.init(any:)))71        default: return nil72        }73    }7475    var any: Any {76        switch self {77        case .null: return NSNull()78        case .bool(let value): return value79        case .number(let value):80            // Whole numbers are written without a fraction ("max_tokens": 1024, not 1024.0).81            if value.isFinite, value == value.rounded(), abs(value) < 9.0e15 { return Int(value) }82            return value.isFinite ? value : 083        case .string(let value): return value84        case .array(let items): return items.map(\.any)85        case .object(let fields): return fields.mapValues(\.any)86        }87    }8889    // MARK: Codable9091    public init(from decoder: Decoder) throws {92        let container = try decoder.singleValueContainer()93        if container.decodeNil() { self = .null }94        else if let value = try? container.decode(Bool.self) { self = .bool(value) }95        else if let value = try? container.decode(Double.self) { self = .number(value) }96        else if let value = try? container.decode(String.self) { self = .string(value) }97        else if let value = try? container.decode([JSONValue].self) { self = .array(value) }98        else { self = .object(try container.decode([String: JSONValue].self)) }99    }100101    public func encode(to encoder: Encoder) throws {102        var container = encoder.singleValueContainer()103        switch self {104        case .null: try container.encodeNil()105        case .bool(let value): try container.encode(value)106        case .number(let value): try container.encode(value)107        case .string(let value): try container.encode(value)108        case .array(let value): try container.encode(value)109        case .object(let value): try container.encode(value)110        }111    }112}113114extension JSONValue: ExpressibleByStringLiteral, ExpressibleByBooleanLiteral, ExpressibleByIntegerLiteral,115    ExpressibleByFloatLiteral, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral, ExpressibleByNilLiteral {116    public init(stringLiteral value: String) { self = .string(value) }117    public init(booleanLiteral value: Bool) { self = .bool(value) }118    public init(integerLiteral value: Int) { self = .number(Double(value)) }119    public init(floatLiteral value: Double) { self = .number(value) }120    public init(arrayLiteral elements: JSONValue...) { self = .array(elements) }121    public init(dictionaryLiteral elements: (String, JSONValue)...) {122        self = .object(Dictionary(elements, uniquingKeysWith: { _, last in last }))123    }124    public init(nilLiteral: ()) { self = .null }125}126
Files main
Menu

Theme