SPB Git

Repository Public

SearchIndex.swift 4.9 KB 118 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Core/Storage/SearchIndex.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// 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          : None specified (no license file in this repository)33//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 Foundation4243/// Local search index. It lives in memory while the vault is unlocked and is44/// persisted only as an encrypted blob (`search.idx`). Nothing is given to45/// Spotlight or any other system index.46struct SearchIndex: Codable, Equatable, Sendable {47    /// Normalised tokens per card, with a weight per source field.48    private(set) var entries: [UUID: [String: Int]] = [:]4950    static func normalize(_ text: String) -> String {51        text.folding(options: [.diacriticInsensitive, .caseInsensitive, .widthInsensitive], locale: nil).lowercased()52    }5354    static func tokens(_ text: String) -> [String] {55        normalize(text).split { !($0.isLetter || $0.isNumber || $0 == "/") }.map(String.init).filter { !$0.isEmpty }56    }5758    private static let monthFormatter: DateFormatter = {59        let f = DateFormatter()60        f.locale = Locale(identifier: "en_US_POSIX")61        f.dateFormat = "MMMM"62        return f63    }()6465    static func expiryTokens(_ date: Date, calendar: Calendar = Calendar(identifier: .gregorian)) -> [String] {66        let c = calendar.dateComponents([.year, .month], from: date)67        guard let year = c.year, let month = c.month else { return [] }68        let mm = String(format: "%02d", month), yy = String(format: "%02d", year % 100)69        return ["\(year)", "\(mm)/\(yy)", "\(mm)/\(year)", "\(year)-\(mm)", normalize(monthFormatter.string(from: date))]70    }7172    mutating func index(_ card: Card, categoryName: String) {73        var weights: [String: Int] = [:]74        func add(_ text: String, _ weight: Int) {75            for token in Self.tokens(text) { weights[token] = max(weights[token] ?? 0, weight) }76        }77        add(card.name, 10)78        add(card.issuer, 7)79        add(card.kind.title, 5)80        add(categoryName, 5)81        add(card.holderName, 4)82        add(card.notes, 2)83        for field in card.fields where !field.isSensitive {84            add(field.label, 2)85            add(field.value, 3)86        }87        if !card.last4.isEmpty { weights[Self.normalize(card.last4)] = 8 }88        if let expiry = card.expiry { for token in Self.expiryTokens(expiry) { weights[token] = 6 } }89        if card.isFavorite { weights["favorite"] = 1 }90        entries[card.id] = weights91    }9293    mutating func remove(_ id: UUID) { entries.removeValue(forKey: id) }9495    /// Every query word must match (exactly or as a prefix) a token of the card.96    func search(_ query: String) -> [UUID] {97        let words = Self.tokens(query)98        guard !words.isEmpty else { return [] }99        var scored: [(UUID, Int)] = []100        for (id, weights) in entries {101            var total = 0102            var matchedAll = true103            for word in words {104                var best = 0105                for (token, weight) in weights {106                    if token == word { best = max(best, weight * 3) }107                    else if token.hasPrefix(word) { best = max(best, weight * 2) }108                    else if word.count >= 3, token.contains(word) { best = max(best, weight) }109                }110                if best == 0 { matchedAll = false; break }111                total += best112            }113            if matchedAll { scored.append((id, total)) }114        }115        return scored.sorted { $0.1 != $1.1 ? $0.1 > $1.1 : $0.0.uuidString < $1.0.uuidString }.map(\.0)116    }117}118
Files main
Menu

Theme