SPB Git

Repository Public MIT

GlassThemeCodec.swift 6.9 KB 161 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassThemes/GlassThemeCodec.swift8// Module           : SPGlassThemes9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243public enum GlassThemeError: Error, Equatable, Sendable, CustomStringConvertible {44    case tooLarge(bytes: Int, limit: Int)45    case notAnObject46    case tooDeep(limit: Int)47    case unsupportedSchema(Int)48    case malformed(String)49    case invalid([String])5051    public var description: String {52        switch self {53        case .tooLarge(let bytes, let limit): "The theme file is \(bytes) bytes; the limit is \(limit)."54        case .notAnObject: "The theme file is not a JSON object."55        case .tooDeep(let limit): "The theme file nests more than \(limit) levels."56        case .unsupportedSchema(let version): "Schema version \(version) is newer than this version of GlassKit (\(GlassKitInfo.schemaVersion))."57        case .malformed(let detail): "The theme file cannot be read: \(detail)"58        case .invalid(let messages): "The theme is invalid: " + messages.joined(separator: " ")59        }60    }61}6263/// Reads and writes theme files. Input is bounded, migrated to the current schema and validated.64public enum GlassThemeCodec {65    public static let maximumBytes = 256 * 102466    public static let maximumDepth = 66768    /// Decodes a theme from JSON. Older schema versions are migrated; a newer version is refused.69    public static func decode(_ data: Data) throws(GlassThemeError) -> GlassTheme {70        guard data.count <= maximumBytes else {71            throw .tooLarge(bytes: data.count, limit: maximumBytes)72        }73        let object: Any74        do {75            object = try JSONSerialization.jsonObject(with: data)76        } catch {77            throw .malformed("it is not valid JSON.")78        }79        guard var dictionary = object as? [String: Any] else { throw .notAnObject }80        guard depth(of: dictionary) <= maximumDepth else { throw .tooDeep(limit: maximumDepth) }8182        dictionary = try migrate(dictionary)8384        let theme: GlassTheme85        do {86            let migrated = try JSONSerialization.data(withJSONObject: dictionary)87            theme = try JSONDecoder().decode(GlassTheme.self, from: migrated)88        } catch let error as DecodingError {89            throw .malformed(describe(error))90        } catch {91            throw .malformed("unexpected structure.")92        }93        let errors = GlassThemeValidator.validate(theme).filter { $0.severity == .error }94        guard errors.isEmpty else { throw .invalid(errors.map(\.message)) }95        return theme96    }9798    /// Encodes a theme as stable, human-readable JSON (sorted keys, two-space indentation).99    public static func encode(_ theme: GlassTheme) throws(GlassThemeError) -> Data {100        let encoder = JSONEncoder()101        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]102        do {103            return try encoder.encode(theme)104        } catch {105            throw .malformed("the theme could not be encoded.")106        }107    }108109    /// Brings a decoded JSON object to the current schema.110    ///111    /// Version 0 (files written before the schema was versioned) stored a single `colors` object, used for112    /// both appearances, and a `cornerRadius` number.113    static func migrate(_ input: [String: Any]) throws(GlassThemeError) -> [String: Any] {114        var dictionary = input115        let version: Int116        switch dictionary["schemaVersion"] {117        case nil: version = dictionary["colors"] != nil ? 0 : GlassKitInfo.schemaVersion118        case let number as Int: version = number119        default: throw .malformed("schemaVersion is not an integer.")120        }121        guard version <= GlassKitInfo.schemaVersion else { throw .unsupportedSchema(version) }122        guard version >= 0 else { throw .malformed("schemaVersion is negative.") }123124        if version == 0 {125            if let colors = dictionary.removeValue(forKey: "colors") {126                if dictionary["light"] == nil { dictionary["light"] = colors }127                if dictionary["dark"] == nil { dictionary["dark"] = colors }128            }129            if let radius = dictionary.removeValue(forKey: "cornerRadius") as? Double, dictionary["radii"] == nil {130                dictionary["radii"] = ["small": radius / 2, "medium": radius, "large": radius * 1.5, "extraLarge": radius * 2]131            }132        }133        dictionary["schemaVersion"] = GlassKitInfo.schemaVersion134        return dictionary135    }136137    private static func depth(of value: Any) -> Int {138        if let dictionary = value as? [String: Any] {139            return 1 + (dictionary.values.map(depth(of:)).max() ?? 0)140        }141        if let array = value as? [Any] {142            return 1 + (array.map(depth(of:)).max() ?? 0)143        }144        return 0145    }146147    private static func describe(_ error: DecodingError) -> String {148        func path(_ context: DecodingError.Context) -> String {149            let keys = context.codingPath.map(\.stringValue).joined(separator: ".")150            return keys.isEmpty ? "root" : keys151        }152        switch error {153        case .keyNotFound(let key, _): return "missing field \"\(key.stringValue)\"."154        case .typeMismatch(_, let context): return "wrong type at \(path(context))."155        case .valueNotFound(_, let context): return "missing value at \(path(context))."156        case .dataCorrupted(let context): return "\(path(context)): \(context.debugDescription)"157        @unknown default: return "unexpected structure."158        }159    }160}161
Files main
Menu

Theme