Intelligence, Advanced Charting & Trading Platform
feat(chartnova): native iOS WidgetKit multi-asset companion
Davood Mehraban committed
Oct 11, 2026 at 16:32 UTC
8cfa215b06f6ca3a512a23b03aaef9b12cad916b
16 files changed
+957
ios/ChartNova/App/ChartNovaApp.swift
new
+12
@@ -0,0 +1,12 @@
1
+import SwiftUI
2
+
3
+@main
4
+struct ChartNovaApp: App {
5
+ var body: some Scene {
6
+ WindowGroup {
7
+ MarketHomeView()
8
+ .environment(\.layoutDirection, .rightToLeft)
9
+ .tint(Color(red: 0.02, green: 0.62, blue: 0.67))
10
+ }
11
+ }
12
+}
ios/ChartNova/App/MarketHomeView.swift
new
+168
@@ -0,0 +1,168 @@
1
+import SwiftUI
2
+import WidgetKit
3
+
4
+struct MarketHomeView: View {
5
+ @StateObject private var model = MarketViewModel()
6
+
7
+ var body: some View {
8
+ TabView {
9
+ NavigationStack {
10
+ List {
11
+ Section {
12
+ VStack(alignment: .leading, spacing: 8) {
13
+ Text("ChartNova").font(.title2.bold()).foregroundStyle(.cyan)
14
+ Text("ویجت چندنمادی آیفون").font(.subheadline)
15
+ Text("قیمتها در میان آیکونهای صفحه اصلی نمایش داده میشوند. اندازه کوچک ۲، متوسط ۴ و بزرگ ۶ نماد نشان میدهد.")
16
+ .font(.footnote).foregroundStyle(.secondary)
17
+ }.padding(.vertical, 8)
18
+ if !WidgetSettingsStore.groupAvailable {
19
+ Label("اشتراک داده App Group فعال نیست. تنظیمات امضای اپ را بررسی کن.", systemImage: "exclamationmark.triangle")
20
+ .font(.footnote).foregroundStyle(.red)
21
+ }
22
+ }
23
+ Section("نمادهای انتخابی · حداکثر ۶") {
24
+ if model.preferences.selectedSymbols.isEmpty {
25
+ Text("از فهرست نمادها، حداقل یک مورد انتخاب کن.").foregroundStyle(.secondary)
26
+ }
27
+ ForEach(model.preferences.selectedSymbols, id: \.self) { symbol in
28
+ selectedRow(symbol)
29
+ }
30
+ .onMove(perform: model.moveSelected)
31
+ }
32
+ Section("ظاهر ویجت") {
33
+ Picker("رنگبندی", selection: Binding(
34
+ get: { model.preferences.appearance },
35
+ set: { model.updateAppearance($0) }
36
+ )) {
37
+ ForEach(WidgetAppearance.allCases) { theme in
38
+ Text(theme.title).tag(theme)
39
+ }
40
+ }.pickerStyle(.segmented)
41
+ }
42
+ Section("وضعیت دریافت داده") {
43
+ if let feed = model.feed {
44
+ LabeledContent("منبع", value: feed.source ?? "نامشخص")
45
+ LabeledContent("زمان دریافت", value: MarketDate.format(feed.fetchedAt))
46
+ if feed.isStale() {
47
+ Label("قیمتها ممکن است قدیمی باشند", systemImage: "clock.badge.exclamationmark")
48
+ .foregroundStyle(.orange)
49
+ }
50
+ } else {
51
+ Text("در انتظار قیمت معتبر").foregroundStyle(.secondary)
52
+ }
53
+ if let error = model.errorMessage {
54
+ Text(error).font(.footnote).foregroundStyle(.orange)
55
+ }
56
+ }
57
+ Section("روش افزودن به صفحه اصلی") {
58
+ Text("پس از نصب و اجرای اپ: روی فضای خالی Home Screen لمس طولانی کن ← Edit ← Add Widget ← جستوجوی ChartNova ← انتخاب اندازه و افزودن.")
59
+ .font(.footnote)
60
+ }
61
+ }
62
+ .navigationTitle("ویجت چارتنوا")
63
+ .toolbar {
64
+ ToolbarItem(placement: .topBarLeading) {
65
+ EditButton()
66
+ }
67
+ ToolbarItem(placement: .topBarTrailing) {
68
+ Button {
69
+ Task { await model.refresh() }
70
+ } label: {
71
+ Image(systemName: "arrow.clockwise")
72
+ }
73
+ .disabled(model.refreshing)
74
+ .accessibilityLabel("تازهسازی قیمت")
75
+ }
76
+ }
77
+ }
78
+ .tabItem { Label("ویجت من", systemImage: "square.grid.2x2") }
79
+
80
+ NavigationStack {
81
+ List {
82
+ Section("جستوجو و انتخاب") {
83
+ Text("ستاره: علاقهمندی · مربع: افزودن به ویجت. محدودیت ۶ نماد.")
84
+ .font(.footnote).foregroundStyle(.secondary)
85
+ ForEach(model.filteredMarkets) { instrument in
86
+ marketRow(instrument)
87
+ }
88
+ if model.markets.isEmpty {
89
+ ContentUnavailableView(
90
+ "دریافت نمادها",
91
+ systemImage: "wifi.exclamationmark",
92
+ description: Text(model.errorMessage ?? "در حال دریافت اطلاعات بازار")
93
+ )
94
+ }
95
+ }
96
+ }
97
+ .searchable(text: $model.search, prompt: "نام یا شناسه نماد، مثلاً GOLD18")
98
+ .navigationTitle("نمادها")
99
+ }
100
+ .tabItem { Label("نمادها", systemImage: "star.circle") }
101
+ }
102
+ .task { await model.refresh() }
103
+ }
104
+
105
+ @ViewBuilder
106
+ private func selectedRow(_ symbol: String) -> some View {
107
+ let quote = model.quote(symbol)
108
+ HStack(spacing: 12) {
109
+ Image(systemName: "line.3.horizontal").foregroundStyle(.secondary)
110
+ VStack(alignment: .leading, spacing: 4) {
111
+ Text(model.name(symbol)).font(.headline)
112
+ Text(symbol).font(.caption.monospaced()).foregroundStyle(.secondary)
113
+ }
114
+ Spacer()
115
+ VStack(alignment: .trailing, spacing: 4) {
116
+ if let quote {
117
+ Text(quote.price.formatted(.number.precision(.fractionLength(0...2))))
118
+ .font(.subheadline.bold()).monospacedDigit()
119
+ Text(quote.quoteLabel).font(.caption2).foregroundStyle(.secondary)
120
+ } else { Text("—").foregroundStyle(.secondary) }
121
+ }
122
+ Button {
123
+ model.toggleSelection(symbol)
124
+ } label: {
125
+ Image(systemName: "minus.circle.fill").foregroundStyle(.red)
126
+ }
127
+ .buttonStyle(.borderless)
128
+ .accessibilityLabel("حذف \(symbol) از ویجت")
129
+ }
130
+ }
131
+
132
+ private func marketRow(_ instrument: CatalogInstrument) -> some View {
133
+ let selected = model.preferences.selectedSymbols.contains(instrument.symbol)
134
+ let favorite = model.preferences.favoriteSymbols.contains(instrument.symbol)
135
+ return HStack(spacing: 10) {
136
+ Button {
137
+ model.toggleFavorite(instrument.symbol)
138
+ } label: {
139
+ Image(systemName: favorite ? "star.fill" : "star")
140
+ .foregroundStyle(favorite ? Color.yellow : Color.secondary)
141
+ }
142
+ .buttonStyle(.borderless)
143
+ .accessibilityLabel(favorite ? "حذف از علاقهمندی" : "افزودن به علاقهمندی")
144
+
145
+ VStack(alignment: .leading, spacing: 3) {
146
+ Text(instrument.name).font(.subheadline.bold())
147
+ Text(instrument.symbol).font(.caption2.monospaced()).foregroundStyle(.secondary)
148
+ }
149
+ Spacer()
150
+ VStack(alignment: .trailing, spacing: 2) {
151
+ Text(instrument.sellPrice.formatted(.number.precision(.fractionLength(0...2))))
152
+ .font(.subheadline.monospacedDigit())
153
+ Text(instrument.quote == "IRT" ? "تومان" : instrument.quote)
154
+ .font(.caption2).foregroundStyle(.secondary)
155
+ }
156
+ Button {
157
+ model.toggleSelection(instrument.symbol)
158
+ } label: {
159
+ Image(systemName: selected ? "checkmark.square.fill" : "plus.square")
160
+ .foregroundStyle(.cyan)
161
+ }
162
+ .buttonStyle(.borderless)
163
+ .disabled(!selected && model.preferences.selectedSymbols.count >= MarketSymbol.maximum)
164
+ .accessibilityLabel(selected ? "حذف از ویجت" : "افزودن به ویجت")
165
+ }
166
+ .padding(.vertical, 3)
167
+ }
168
+}
ios/ChartNova/App/MarketViewModel.swift
new
+97
@@ -0,0 +1,97 @@
1
+import SwiftUI
2
+import WidgetKit
3
+
4
+@MainActor
5
+final class MarketViewModel: ObservableObject {
6
+ @Published private(set) var markets: [CatalogInstrument] = []
7
+ @Published private(set) var feed: WidgetFeed?
8
+ @Published private(set) var preferences: WidgetPreferences = WidgetSettingsStore.load()
9
+ @Published private(set) var refreshing = false
10
+ @Published var search = ""
11
+ @Published var errorMessage: String?
12
+
13
+ var filteredMarkets: [CatalogInstrument] {
14
+ let query = search.trimmingCharacters(in: .whitespacesAndNewlines)
15
+ let ordered = markets.sorted {
16
+ let favA = preferences.favoriteSymbols.contains($0.symbol)
17
+ let favB = preferences.favoriteSymbols.contains($1.symbol)
18
+ return favA == favB ? $0.symbol < $1.symbol : favA
19
+ }
20
+ if query.isEmpty { return ordered }
21
+ return ordered.filter {
22
+ $0.symbol.localizedCaseInsensitiveContains(query) ||
23
+ $0.name.localizedCaseInsensitiveContains(query)
24
+ }
25
+ }
26
+
27
+ func quote(_ symbol: String) -> MarketQuote? {
28
+ feed?.items.first(where: { $0.symbol == symbol })
29
+ }
30
+
31
+ func name(_ symbol: String) -> String {
32
+ markets.first(where: { $0.symbol == symbol })?.name ?? symbol
33
+ }
34
+
35
+ func refresh() async {
36
+ guard !refreshing else { return }
37
+ refreshing = true
38
+ defer { refreshing = false }
39
+ errorMessage = nil
40
+
41
+ do {
42
+ markets = try await MarketAPI().fetchCatalog()
43
+ } catch {
44
+ errorMessage = "دریافت فهرست نمادها ناموفق بود: \(error.localizedDescription)"
45
+ }
46
+ do {
47
+ let selected = preferences.selectedSymbols
48
+ if !selected.isEmpty {
49
+ feed = try await MarketAPI().fetchWidget(symbols: selected)
50
+ if let feed { WidgetQuoteCache.save(feed) }
51
+ } else { feed = nil }
52
+ } catch {
53
+ feed = WidgetQuoteCache.load()
54
+ let detail = "قیمت تازه دریافت نشد؛ در صورت وجود آخرین داده ذخیرهشده نمایش داده میشود."
55
+ errorMessage = [errorMessage, detail].compactMap { $0 }.joined(separator: "\n")
56
+ }
57
+ }
58
+
59
+ func toggleFavorite(_ symbol: String) {
60
+ preferences.toggleFavorite(symbol)
61
+ persist()
62
+ }
63
+
64
+ func toggleSelection(_ symbol: String) {
65
+ preferences.toggleSelection(symbol)
66
+ persist()
67
+ Task { await refreshQuotesOnly() }
68
+ }
69
+
70
+ func updateAppearance(_ value: WidgetAppearance) {
71
+ preferences.appearance = value
72
+ persist()
73
+ }
74
+
75
+ func moveSelected(from indices: IndexSet, to destination: Int) {
76
+ preferences.selectedSymbols.move(fromOffsets: indices, toOffset: destination)
77
+ persist()
78
+ }
79
+
80
+ private func persist() {
81
+ WidgetSettingsStore.save(preferences)
82
+ WidgetCenter.shared.reloadTimelines(ofKind: "ChartNovaMultiAssetWidget")
83
+ }
84
+
85
+ private func refreshQuotesOnly() async {
86
+ let symbols = preferences.selectedSymbols
87
+ if symbols.isEmpty { feed = nil; return }
88
+ do {
89
+ let result = try await MarketAPI().fetchWidget(symbols: symbols)
90
+ feed = result
91
+ WidgetQuoteCache.save(result)
92
+ } catch {
93
+ feed = WidgetQuoteCache.load()
94
+ }
95
+ WidgetCenter.shared.reloadTimelines(ofKind: "ChartNovaMultiAssetWidget")
96
+ }
97
+}
ios/ChartNova/README.md
new
+38
@@ -0,0 +1,38 @@
1
+# ChartNova iOS + real WidgetKit extension
2
+
3
+This folder contains the **native iPhone companion app and Home Screen widget source**, not a web shortcut. Unlike a PWA, the WidgetKit target appears in the iOS **Add Widget** picker after the containing app has been built, signed and installed.
4
+
5
+## Features
6
+
7
+- One widget with the standard iOS small, medium and large families, showing **2 / 4 / 6** user-selected instruments respectively.
8
+- App screen to select up to six market symbols from ChartNova's live 58-symbol watchlist, favorite/unfavorite, reorder and choose Nova Glass, dark or light appearance.
9
+- Shared App Group `group.ir.chartnova.widgets` persists preferences between app and widget.
10
+- HTTPS `GET https://app.chartnova.ir/api/widget?symbols=...` with the selected ordered symbols. Zero API keys in the binary; request is served by Cloudflare KV and does not consume 250-per-day upstream requests per widget view.
11
+- WidgetKit timeline asks for a refresh after 15 minutes; **iOS may defer updates** depending on power, budget, connectivity and system policy.
12
+- When offline, last valid response is used and prominently marked as cached / stale. Placeholder **does not invent prices**.
13
+- Tapping widget opens the companion app through `chartnova://widget`.
14
+
15
+## Building on macOS (required)
16
+
17
+1. Use a Mac with an Xcode version that supports iOS 17 or later.
18
+2. Install **XcodeGen** (e.g. `brew install xcodegen`).
19
+3. Run `cd ios/ChartNova && xcodegen generate`, then open `ChartNova.xcodeproj` in Xcode.
20
+4. Select your Apple development team under Signing & Capabilities for both `ChartNova` and `ChartNovaWidgets`.
21
+5. Register and enable the same **App Groups** capability, `group.ir.chartnova.widgets`, for both bundle IDs. Change the sample bundle IDs and group ID if your team's identifiers are different; update both `project.yml` and `Shared/WidgetSettings.swift`.
22
+6. Build and run the **ChartNova** scheme on your physical iPhone; trust the developer identity if prompted.
23
+7. Open ChartNova once, select favorites and rearrange the widget list. On the iPhone Home Screen, long-press empty space → **Edit → Add Widget** → search **ChartNova** → choose a size → Add Widget.
24
+8. For iOS unit tests run `xcodebuild test -project ChartNova.xcodeproj -scheme ChartNova -destination 'platform=iOS Simulator,name=iPhone 16'`; choose an available simulator name if different.
25
+
26
+The App Group and development provisioning are Apple-controlled; without them the widget cannot securely share app preferences. A paid Apple Developer membership may be required for distribution and/or capabilities. Nothing has been published to the App Store or installed on an actual iPhone by this repository change.
27
+
28
+## Security & correctness
29
+
30
+- Uses HTTPS-only ChartNova backend. No credentials, bearer tokens or API secret keys in the app.
31
+- All selected symbols are allowlisted to uppercase `BASE-QUOTE` pairs with a six-symbol cap.
32
+- Network data is decoded and validated before being cached, with explicit provider timestamps / stale indicators.
33
+- Price values are **provider sell quotes**, not necessarily executable exchange prices, and are not guaranteed to update in real time.
34
+- The iOS application and widget targets share code from `Shared/`. Native widget settings are separate from the browser's localStorage-based preview; automatic cross-device/browser sync requires account support and has **not** been built.
35
+
36
+## Validation evidence
37
+
38
+Automated tests against the real live ChartNova widget API and static project validation are possible from Windows/Linux. **Xcode compilation, simulator WidgetKit integration and physical iPhone installation require macOS/Xcode and must not be claimed passed until run.**
ios/ChartNova/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png
Binary files /dev/null and b/ios/ChartNova/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon-1024.png differ
ios/ChartNova/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
new
+11
@@ -0,0 +1,11 @@
1
+{
2
+ "images": [
3
+ {
4
+ "filename": "AppIcon-1024.png",
5
+ "idiom": "universal",
6
+ "platform": "ios",
7
+ "size": "1024x1024"
8
+ }
9
+ ],
10
+ "info": { "author": "xcode", "version": 1 }
11
+}
ios/ChartNova/Resources/Generate-Icon.ps1
new
+37
@@ -0,0 +1,37 @@
1
+$ErrorActionPreference = "Stop"
2
+Add-Type -AssemblyName System.Drawing
3
+$destination = Join-Path $PSScriptRoot "Assets.xcassets\AppIcon.appiconset\AppIcon-1024.png"
4
+$bmp = New-Object System.Drawing.Bitmap(1024, 1024)
5
+$g = [System.Drawing.Graphics]::FromImage($bmp)
6
+$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
7
+$rect = New-Object System.Drawing.Rectangle(0, 0, 1024, 1024)
8
+$col1 = [System.Drawing.ColorTranslator]::FromHtml("#e5f8f7")
9
+$col2 = [System.Drawing.ColorTranslator]::FromHtml("#b8e9f2")
10
+$bg = New-Object System.Drawing.Drawing2D.LinearGradientBrush($rect, $col1, $col2, 45)
11
+$g.FillRectangle($bg, $rect)
12
+$deep = [System.Drawing.ColorTranslator]::FromHtml("#087F99")
13
+$cyan = [System.Drawing.ColorTranslator]::FromHtml("#1CB9BE")
14
+$white = [System.Drawing.Color]::FromArgb(180, 255, 255, 255)
15
+$pen = New-Object System.Drawing.Pen($cyan, 86)
16
+$pen.StartCap = [System.Drawing.Drawing2D.LineCap]::Round
17
+$pen.EndCap = [System.Drawing.Drawing2D.LineCap]::Round
18
+$g.DrawArc($pen, 172, 180, 650, 650, 42, 274)
19
+$orb = New-Object System.Drawing.Pen($white, 30)
20
+$g.DrawEllipse($orb, 180, 435, 660, 235)
21
+$bars = New-Object System.Drawing.SolidBrush($deep)
22
+$g.FillRectangle($bars, 365, 500, 95, 250)
23
+$g.FillRectangle($bars, 500, 390, 95, 350)
24
+$g.FillRectangle($bars, 635, 310, 95, 375)
25
+$accentPen = New-Object System.Drawing.Pen($cyan, 24)
26
+$g.DrawLine($accentPen, 680, 280, 790, 195)
27
+$g.DrawLine($accentPen, 720, 197, 790, 195)
28
+$g.DrawLine($accentPen, 790, 195, 780, 260)
29
+$bmp.Save($destination, [System.Drawing.Imaging.ImageFormat]::Png)
30
+$g.Dispose()
31
+$bmp.Dispose()
32
+$bg.Dispose()
33
+$pen.Dispose()
34
+$orb.Dispose()
35
+$bars.Dispose()
36
+$accentPen.Dispose()
37
+Write-Output "Icon saved: $destination"
ios/ChartNova/Shared/MarketAPI.swift
new
+58
@@ -0,0 +1,58 @@
1
+import Foundation
2
+#if canImport(FoundationNetworking)
3
+import FoundationNetworking
4
+#endif
5
+
6
+enum MarketAPIError: LocalizedError {
7
+ case invalidSelection, invalidResponse, server(Int)
8
+ var errorDescription: String? {
9
+ switch self {
10
+ case .invalidSelection: return "شناسه نمادهای انتخابشده معتبر نیست."
11
+ case .invalidResponse: return "پاسخ معتبر از ChartNova دریافت نشد."
12
+ case .server(let code): return "سرویس بازار در دسترس نیست (HTTP \(code))."
13
+ }
14
+ }
15
+}
16
+struct MarketAPI {
17
+ static let baseURL = URL(string: "https://app.chartnova.ir")!
18
+ var session: URLSession = .shared
19
+
20
+ func fetchWidget(symbols: [String]) async throws -> WidgetFeed {
21
+ let clean = MarketSymbol.unique(symbols)
22
+ guard !clean.isEmpty else { throw MarketAPIError.invalidSelection }
23
+ var parts = URLComponents(url: Self.baseURL.appendingPathComponent("api/widget"), resolvingAgainstBaseURL: false)!
24
+ parts.queryItems = [URLQueryItem(name: "symbols", value: clean.joined(separator: ","))]
25
+ guard let url = parts.url else { throw MarketAPIError.invalidSelection }
26
+ let req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 12)
27
+ let (data, response) = try await session.data(for: req)
28
+ guard let http = response as? HTTPURLResponse else { throw MarketAPIError.invalidResponse }
29
+ guard http.statusCode == 200 else { throw MarketAPIError.server(http.statusCode) }
30
+ let feed = try JSONDecoder().decode(WidgetFeed.self, from: data)
31
+ guard feed.ok, !feed.items.isEmpty, feed.items.count <= MarketSymbol.maximum,
32
+ feed.items.allSatisfy({ MarketSymbol.isValid($0.symbol) && $0.price.isFinite && $0.price > 0 }) else { throw MarketAPIError.invalidResponse }
33
+ return feed
34
+ }
35
+
36
+ func fetchCatalog() async throws -> [CatalogInstrument] {
37
+ let req = URLRequest(url: Self.baseURL.appendingPathComponent("api/markets"), cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
38
+ let (data, response) = try await session.data(for: req)
39
+ guard let http = response as? HTTPURLResponse else { throw MarketAPIError.invalidResponse }
40
+ guard http.statusCode == 200 else { throw MarketAPIError.server(http.statusCode) }
41
+ let catalog = try JSONDecoder().decode(MarketCatalogResponse.self, from: data)
42
+ guard catalog.ok, !catalog.markets.isEmpty else { throw MarketAPIError.invalidResponse }
43
+ return catalog.markets.filter { MarketSymbol.isValid($0.symbol) && $0.sellPrice.isFinite && $0.sellPrice > 0 }
44
+ }
45
+}
46
+enum WidgetQuoteCache {
47
+ private static let key = "chartnova.widget.lastValidFeed.v1"
48
+ static func save(_ feed: WidgetFeed) {
49
+ guard feed.ok, !feed.items.isEmpty, let data = try? JSONEncoder().encode(feed) else { return }
50
+ WidgetSettingsStore.defaults.set(data, forKey: key)
51
+ }
52
+ static func load() -> WidgetFeed? {
53
+ guard let data = WidgetSettingsStore.defaults.data(forKey: key),
54
+ let feed = try? JSONDecoder().decode(WidgetFeed.self, from: data),
55
+ feed.ok, !feed.items.isEmpty else { return nil }
56
+ return feed
57
+ }
58
+}
ios/ChartNova/Shared/MarketModels.swift
new
+81
@@ -0,0 +1,81 @@
1
+import Foundation
2
+
3
+enum MarketSymbol {
4
+ static let defaults = ["USD-IRT", "GOLD18-IRT", "USDT-IRT", "EUR-IRT"]
5
+ static let maximum = 6
6
+ static func isValid(_ value: String) -> Bool {
7
+ let components = value.split(separator: "-", omittingEmptySubsequences: false)
8
+ guard components.count == 2,
9
+ (1...20).contains(components[0].count),
10
+ (2...10).contains(components[1].count) else { return false }
11
+ return components.allSatisfy { part in
12
+ part.utf8.allSatisfy { (65...90).contains($0) || (48...57).contains($0) }
13
+ }
14
+ }
15
+ static func unique(_ symbols: [String], limit: Int = maximum) -> [String] {
16
+ var seen = Set<String>()
17
+ return Array(symbols.filter { isValid($0) && seen.insert($0).inserted }.prefix(limit))
18
+ }
19
+}
20
+
21
+struct MarketQuote: Codable, Identifiable, Equatable {
22
+ let symbol: String
23
+ let name: String
24
+ let quote: String
25
+ let price: Double
26
+ let changePercent: Double?
27
+ let providerUpdatedAt: String?
28
+ let providerSaysFresh: Bool?
29
+ var id: String { symbol }
30
+ var quoteLabel: String {
31
+ switch quote {
32
+ case "IRT": return "تومان"
33
+ case "USD": return "دلار"
34
+ default: return quote
35
+ }
36
+ }
37
+}
38
+
39
+struct WidgetFeed: Codable, Equatable {
40
+ let ok: Bool
41
+ let source: String?
42
+ let quoteSide: String?
43
+ let fetchedAt: String?
44
+ let stale: Bool?
45
+ let refreshAfterSeconds: Int?
46
+ let items: [MarketQuote]
47
+ let missingSymbols: [String]?
48
+
49
+ func isStale(at now: Date = Date()) -> Bool {
50
+ guard let fetchedAt, let fetched = MarketDate.parse(fetchedAt) else { return true }
51
+ return stale == true || now.timeIntervalSince(fetched) > 45 * 60
52
+ }
53
+}
54
+struct CatalogInstrument: Codable, Identifiable, Equatable {
55
+ let symbol: String
56
+ let name: String
57
+ let quote: String
58
+ let category: String?
59
+ let sellPrice: Double
60
+ let change: Double?
61
+ let updatedAt: String?
62
+ var id: String { symbol }
63
+}
64
+struct MarketCatalogResponse: Decodable {
65
+ let ok: Bool
66
+ let markets: [CatalogInstrument]
67
+}
68
+enum MarketDate {
69
+ static func parse(_ text: String) -> Date? {
70
+ let withFraction = ISO8601DateFormatter()
71
+ withFraction.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
72
+ if let date = withFraction.date(from: text) { return date }
73
+ let standard = ISO8601DateFormatter()
74
+ standard.formatOptions = [.withInternetDateTime]
75
+ return standard.date(from: text)
76
+ }
77
+ static func format(_ raw: String?) -> String {
78
+ guard let raw, let date = parse(raw) else { return "زمان نامشخص" }
79
+ return date.formatted(date: .omitted, time: .shortened)
80
+ }
81
+}
ios/ChartNova/Shared/WidgetSettings.swift
new
+49
@@ -0,0 +1,49 @@
1
+import Foundation
2
+
3
+enum WidgetAppearance: String, Codable, CaseIterable, Identifiable {
4
+ case glass, dark, light
5
+ var id: String { rawValue }
6
+ var title: String {
7
+ switch self {
8
+ case .glass: return "Nova Glass"
9
+ case .dark: return "تیره"
10
+ case .light: return "روشن"
11
+ }
12
+ }
13
+}
14
+struct WidgetPreferences: Codable, Equatable {
15
+ var selectedSymbols: [String]
16
+ var favoriteSymbols: [String]
17
+ var appearance: WidgetAppearance
18
+ static let initial = WidgetPreferences(selectedSymbols: MarketSymbol.defaults, favoriteSymbols: MarketSymbol.defaults, appearance: .glass)
19
+ func normalized() -> WidgetPreferences {
20
+ WidgetPreferences(selectedSymbols: MarketSymbol.unique(selectedSymbols), favoriteSymbols: MarketSymbol.unique(favoriteSymbols, limit: 100), appearance: appearance)
21
+ }
22
+ mutating func toggleFavorite(_ symbol: String) {
23
+ guard MarketSymbol.isValid(symbol) else { return }
24
+ if favoriteSymbols.contains(symbol) { favoriteSymbols.removeAll { $0 == symbol } }
25
+ else { favoriteSymbols.append(symbol) }
26
+ favoriteSymbols = MarketSymbol.unique(favoriteSymbols, limit: 100)
27
+ }
28
+ mutating func toggleSelection(_ symbol: String) {
29
+ guard MarketSymbol.isValid(symbol) else { return }
30
+ if selectedSymbols.contains(symbol) { selectedSymbols.removeAll { $0 == symbol } }
31
+ else if selectedSymbols.count < MarketSymbol.maximum { selectedSymbols.append(symbol) }
32
+ }
33
+}
34
+enum WidgetSettingsStore {
35
+ static let appGroupID = "group.ir.chartnova.widgets"
36
+ private static let preferencesKey = "chartnova.widget.preferences.v1"
37
+ static var groupAvailable: Bool { UserDefaults(suiteName: appGroupID) != nil }
38
+ static var defaults: UserDefaults { UserDefaults(suiteName: appGroupID) ?? .standard }
39
+
40
+ static func load() -> WidgetPreferences {
41
+ guard let data = defaults.data(forKey: preferencesKey),
42
+ let result = try? JSONDecoder().decode(WidgetPreferences.self, from: data) else { return .initial }
43
+ return result.normalized()
44
+ }
45
+ static func save(_ preferences: WidgetPreferences) {
46
+ guard let data = try? JSONEncoder().encode(preferences.normalized()) else { return }
47
+ defaults.set(data, forKey: preferencesKey)
48
+ }
49
+}
ios/ChartNova/Tests/ChartNovaCoreTests.swift
new
+64
@@ -0,0 +1,64 @@
1
+import XCTest
2
+@testable import ChartNova
3
+
4
+final class ChartNovaCoreTests: XCTestCase {
5
+ func testDefaultsInclude18KGoldAndMultipleCurrencies() {
6
+ let prefs = WidgetPreferences.initial
7
+ XCTAssertEqual(prefs.selectedSymbols, ["USD-IRT", "GOLD18-IRT", "USDT-IRT", "EUR-IRT"])
8
+ XCTAssertEqual(prefs.appearance, .glass)
9
+ }
10
+
11
+ func testMaximumSixAndNoDuplicateOrInvalidSymbols() {
12
+ let raw = ["USD-IRT", "USD-IRT", "<script>", "GOLD18-IRT", "BTC-USD", "EUR-IRT", "USDT-IRT", "SEKE-IRT", "ETH-USD"]
13
+ XCTAssertEqual(MarketSymbol.unique(raw), ["USD-IRT", "GOLD18-IRT", "BTC-USD", "EUR-IRT", "USDT-IRT", "SEKE-IRT"])
14
+ XCTAssertFalse(MarketSymbol.isValid("foo/evil"))
15
+ }
16
+
17
+ func testFavoritesAndSelectionsCanToggle() {
18
+ var prefs = WidgetPreferences.initial
19
+ prefs.toggleFavorite("BTC-USD")
20
+ XCTAssertTrue(prefs.favoriteSymbols.contains("BTC-USD"))
21
+ prefs.toggleFavorite("BTC-USD")
22
+ XCTAssertFalse(prefs.favoriteSymbols.contains("BTC-USD"))
23
+ prefs.toggleSelection("GOLD18-IRT")
24
+ XCTAssertFalse(prefs.selectedSymbols.contains("GOLD18-IRT"))
25
+ prefs.toggleSelection("GOLD18-IRT")
26
+ XCTAssertTrue(prefs.selectedSymbols.contains("GOLD18-IRT"))
27
+ }
28
+
29
+ func testProviderJSONDecodesCorrectQuoteCurrencyAndStaleState() throws {
30
+ let json = #"""
31
+ {
32
+ "ok":true,"source":"gheymat.online","quoteSide":"sell",
33
+ "fetchedAt":"2026-10-11T10:30:52.347Z","stale":false,
34
+ "refreshAfterSeconds":900,"missingSymbols":[],
35
+ "items":[
36
+ {"symbol":"USD-IRT","name":"دلار آمریکا","quote":"IRT","price":265060,
37
+ "changePercent":-0.3,"providerUpdatedAt":"2026-10-11T10:30:45.033191Z","providerSaysFresh":true},
38
+ {"symbol":"GOLD18-IRT","name":"طلای ۱۸ عیار","quote":"IRT","price":26235860,
39
+ "changePercent":0.7,"providerUpdatedAt":"2026-10-11T10:30:45.032870Z","providerSaysFresh":true},
40
+ {"symbol":"BTC-USD","name":"بیت کوین","quote":"USD","price":100000,
41
+ "changePercent":1.2,"providerUpdatedAt":null,"providerSaysFresh":true}
42
+ ]
43
+ }
44
+ """#
45
+ let feed = try JSONDecoder().decode(WidgetFeed.self, from: Data(json.utf8))
46
+ XCTAssertEqual(feed.items.count, 3)
47
+ XCTAssertEqual(feed.items[1].price, 26235860)
48
+ XCTAssertEqual(feed.items[1].quoteLabel, "تومان")
49
+ XCTAssertEqual(feed.items[2].quoteLabel, "دلار")
50
+ XCTAssertEqual(feed.quoteSide, "sell")
51
+ XCTAssertNotNil(MarketDate.parse(feed.fetchedAt!))
52
+ XCTAssertTrue(feed.isStale(at: Date(timeIntervalSince1970: 2_000_000_000)))
53
+ }
54
+
55
+ func testNormalizationKeepsOrderAndBounds() {
56
+ let prefs = WidgetPreferences(
57
+ selectedSymbols: ["BTC-USD", "GOLD18-IRT", "BTC-USD", "FOO-IRT"],
58
+ favoriteSymbols: ["USD-IRT", "USD-IRT", "EUR-IRT"],
59
+ appearance: .dark
60
+ ).normalized()
61
+ XCTAssertEqual(prefs.selectedSymbols, ["BTC-USD", "GOLD18-IRT", "FOO-IRT"])
62
+ XCTAssertEqual(prefs.favoriteSymbols, ["USD-IRT", "EUR-IRT"])
63
+ }
64
+}
ios/ChartNova/Tests/verify-live-api.cjs
new
+25
@@ -0,0 +1,25 @@
1
+const assert=require('node:assert/strict');const {setTimeout:pause}=require('node:timers/promises');
2
+const base='https://app.chartnova.ir';
3
+async function get(path){let last;for(let i=0;i<3;i++){try{const r=await fetch(base+path,{signal:AbortSignal.timeout(14000),headers:{Accept:'application/json'}});const value=await r.json();return {status:r.status,value}}catch(e){last=e;await pause(500)}}throw last}
4
+(async()=>{
5
+ const requested=['GOLD18-IRT','USD-IRT','USDT-IRT','BTC-USD','EUR-IRT','SEKE-IRT'];
6
+ const reply=await get('/api/widget?symbols='+requested.join(','));
7
+ assert.equal(reply.status,200);assert.equal(reply.value.ok,true);
8
+ assert.deepEqual(reply.value.items.map(x=>x.symbol),requested);
9
+ assert.equal(reply.value.refreshAfterSeconds,900);
10
+ assert.equal(reply.value.items[0].quote,'IRT');assert.equal(reply.value.items[3].quote,'USD');
11
+ assert(reply.value.items.every(x=>Number.isFinite(x.price)&&x.price>0));
12
+ console.log('PASS six ordered real quotes, currencies, gold and crypto',reply.value.source,reply.value.fetchedAt);
13
+ const c=await get('/api/markets');assert.equal(c.status,200);assert(c.value.markets.length>=40);
14
+ assert(c.value.markets.some(x=>x.symbol==='GOLD18-IRT'));
15
+ console.log('PASS public catalog',c.value.markets.length);
16
+ const tooMany=await get('/api/widget?symbols=USD-IRT,GOLD18-IRT,BTC-USD,EUR-IRT,USDT-IRT,SEKE-IRT,ETH-USD');
17
+ assert.equal(tooMany.status,400);console.log('PASS cap six');
18
+ const malformed=await get('/api/widget?symbols=%3Cscript%3E');
19
+ assert.equal(malformed.status,400);console.log('PASS input validation');
20
+ const unknown=await get('/api/widget?symbols=USD-IRT,NOTREAL-IRT');
21
+ assert.equal(unknown.status,200);
22
+ assert.deepEqual(unknown.value.missingSymbols,['NOTREAL-IRT']);
23
+ console.log('PASS explicit missing symbols');
24
+ console.log('ALL 5 LIVE API CHECKS PASSED');
25
+})().catch(e=>{console.error('FAIL',e);process.exitCode=1});
ios/ChartNova/WidgetExtension/ChartNovaWidget.swift
new
+85
@@ -0,0 +1,85 @@
1
+import SwiftUI
2
+import WidgetKit
3
+
4
+struct ChartNovaTimelineEntry: TimelineEntry {
5
+ let date: Date
6
+ let selectedSymbols: [String]
7
+ let appearance: WidgetAppearance
8
+ let quotes: [MarketQuote]
9
+ let fetchedAt: String?
10
+ let source: String
11
+ let stale: Bool
12
+ let usedOfflineCache: Bool
13
+
14
+ func quote(for symbol: String) -> MarketQuote? {
15
+ quotes.first(where: { $0.symbol == symbol })
16
+ }
17
+}
18
+
19
+struct ChartNovaTimelineProvider: TimelineProvider {
20
+ func placeholder(in context: Context) -> ChartNovaTimelineEntry {
21
+ entry(quotes: [], fetchedAt: nil, source: "ChartNova", stale: true, offline: false)
22
+ }
23
+
24
+ func getSnapshot(in context: Context, completion: @escaping (ChartNovaTimelineEntry) -> Void) {
25
+ if context.isPreview {
26
+ completion(placeholder(in: context))
27
+ } else {
28
+ Task { completion(await downloadEntry()) }
29
+ }
30
+ }
31
+
32
+ func getTimeline(in context: Context, completion: @escaping (Timeline<ChartNovaTimelineEntry>) -> Void) {
33
+ Task {
34
+ let current = await downloadEntry()
35
+ // System decides when to honor this request; 15 minutes is not guaranteed.
36
+ let earliestRefresh = Date().addingTimeInterval(current.usedOfflineCache ? 5 * 60 : 15 * 60)
37
+ completion(Timeline(entries: [current], policy: .after(earliestRefresh)))
38
+ }
39
+ }
40
+
41
+ private func downloadEntry() async -> ChartNovaTimelineEntry {
42
+ let config = WidgetSettingsStore.load()
43
+ guard !config.selectedSymbols.isEmpty else {
44
+ return entry(quotes: [], fetchedAt: nil, source: "ChartNova", stale: true, offline: false)
45
+ }
46
+ do {
47
+ let feed = try await MarketAPI().fetchWidget(symbols: config.selectedSymbols)
48
+ WidgetQuoteCache.save(feed)
49
+ return entry(quotes: feed.items, fetchedAt: feed.fetchedAt, source: feed.source ?? "ChartNova",
50
+ stale: feed.isStale() || feed.items.contains(where: { $0.providerSaysFresh == false }),
51
+ offline: false, prefs: config)
52
+ } catch {
53
+ let cached = WidgetQuoteCache.load()
54
+ return entry(quotes: cached?.items ?? [], fetchedAt: cached?.fetchedAt, source: cached?.source ?? "ChartNova",
55
+ stale: true, offline: true, prefs: config)
56
+ }
57
+ }
58
+
59
+ private func entry(quotes: [MarketQuote], fetchedAt: String?, source: String, stale: Bool,
60
+ offline: Bool, prefs: WidgetPreferences = WidgetSettingsStore.load()) -> ChartNovaTimelineEntry {
61
+ ChartNovaTimelineEntry(date: Date(), selectedSymbols: prefs.selectedSymbols,
62
+ appearance: prefs.appearance, quotes: quotes, fetchedAt: fetchedAt,
63
+ source: source, stale: stale, usedOfflineCache: offline)
64
+ }
65
+}
66
+
67
+struct ChartNovaWidget: Widget {
68
+ let kind = "ChartNovaMultiAssetWidget"
69
+
70
+ var body: some WidgetConfiguration {
71
+ StaticConfiguration(kind: kind, provider: ChartNovaTimelineProvider()) { entry in
72
+ ChartNovaWidgetView(entry: entry)
73
+ }
74
+ .configurationDisplayName("چارتنوا | قیمتهای منتخب")
75
+ .description("چند ارز، تتر، سکه و گرم طلا را در صفحه اصلی آیفون ببین.")
76
+ .supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
77
+ }
78
+}
79
+
80
+@main
81
+struct ChartNovaWidgetBundle: WidgetBundle {
82
+ var body: some Widget {
83
+ ChartNovaWidget()
84
+ }
85
+}
ios/ChartNova/WidgetExtension/ChartNovaWidgetView.swift
new
+131
@@ -0,0 +1,131 @@
1
+import SwiftUI
2
+import WidgetKit
3
+
4
+struct ChartNovaWidgetView: View {
5
+ @Environment(\.widgetFamily) private var family
6
+ let entry: ChartNovaTimelineEntry
7
+
8
+ private var capacity: Int {
9
+ switch family {
10
+ case .systemSmall: return 2
11
+ case .systemMedium: return 4
12
+ case .systemLarge: return 6
13
+ default: return 2
14
+ }
15
+ }
16
+
17
+ private var columns: [GridItem] {
18
+ family == .systemSmall
19
+ ? [GridItem(.flexible(), spacing: 6)]
20
+ : [GridItem(.flexible(), spacing: 7), GridItem(.flexible(), spacing: 7)]
21
+ }
22
+
23
+ private var background: [Color] {
24
+ switch entry.appearance {
25
+ case .glass: return [Color(red: 0.89, green: 0.99, blue: 0.98), Color(red: 0.83, green: 0.93, blue: 0.97)]
26
+ case .dark: return [Color(red: 0.07, green: 0.15, blue: 0.23), Color(red: 0.04, green: 0.09, blue: 0.15)]
27
+ case .light: return [.white, Color(red: 0.94, green: 0.96, blue: 0.99)]
28
+ }
29
+ }
30
+
31
+ private var foreground: Color { entry.appearance == .dark ? .white : Color(red: 0.09, green: 0.23, blue: 0.29) }
32
+ private var subdued: Color { entry.appearance == .dark ? Color(red: 0.66, green: 0.78, blue: 0.82) : Color(red: 0.33, green: 0.48, blue: 0.53) }
33
+ private var accent: Color { entry.appearance == .dark ? Color(red: 0.45, green: 0.91, blue: 0.86) : Color(red: 0.02, green: 0.58, blue: 0.64) }
34
+
35
+ var body: some View {
36
+ VStack(alignment: .leading, spacing: family == .systemSmall ? 5 : 9) {
37
+ header
38
+ if entry.selectedSymbols.isEmpty {
39
+ Text("نمادها را در اپ ChartNova انتخاب کن.")
40
+ .font(.caption2).foregroundStyle(subdued)
41
+ Spacer(minLength: 0)
42
+ } else {
43
+ LazyVGrid(columns: columns, alignment: .leading, spacing: family == .systemSmall ? 7 : 10) {
44
+ ForEach(Array(entry.selectedSymbols.prefix(capacity)), id: \.self) { symbol in
45
+ quoteCell(symbol)
46
+ }
47
+ }
48
+ Spacer(minLength: 0)
49
+ }
50
+ footer
51
+ }
52
+ .padding(family == .systemSmall ? 11 : 14)
53
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
54
+ .environment(\.layoutDirection, .rightToLeft)
55
+ .containerBackground(for: .widget) {
56
+ LinearGradient(colors: background, startPoint: .topLeading, endPoint: .bottomTrailing)
57
+ }
58
+ .widgetURL(URL(string: "chartnova://widget"))
59
+ }
60
+
61
+ private var header: some View {
62
+ HStack(spacing: 4) {
63
+ Image(systemName: "chart.bar.fill").font(.system(size: family == .systemSmall ? 12 : 15))
64
+ Text("ChartNova").font(.system(size: family == .systemSmall ? 11 : 14, weight: .bold))
65
+ Spacer(minLength: 0)
66
+ if entry.stale {
67
+ Image(systemName: "clock.badge.exclamationmark")
68
+ .font(.system(size: 10))
69
+ .accessibilityLabel("قیمت قدیمی")
70
+ } else {
71
+ Circle().fill(Color.green).frame(width: 6, height: 6)
72
+ }
73
+ }
74
+ .foregroundStyle(accent)
75
+ }
76
+
77
+ private func quoteCell(_ symbol: String) -> some View {
78
+ let quote = entry.quote(for: symbol)
79
+ return VStack(alignment: .leading, spacing: family == .systemSmall ? 2 : 3) {
80
+ Text(quote?.name ?? symbol)
81
+ .font(.system(size: family == .systemSmall ? 10 : 11, weight: .semibold))
82
+ .lineLimit(1)
83
+ .foregroundStyle(foreground)
84
+
85
+ HStack(alignment: .firstTextBaseline, spacing: 3) {
86
+ Text(quote.map { formatPrice($0.price) } ?? "—")
87
+ .font(.system(size: family == .systemSmall ? 13 : 15, weight: .bold, design: .rounded))
88
+ .lineLimit(1)
89
+ .minimumScaleFactor(0.65)
90
+ .monospacedDigit()
91
+ .foregroundStyle(foreground)
92
+ Spacer(minLength: 0)
93
+ }
94
+ HStack(spacing: 4) {
95
+ Text(quote?.quoteLabel ?? "—")
96
+ .font(.system(size: 8))
97
+ .foregroundStyle(subdued)
98
+ .lineLimit(1)
99
+ if let change = quote?.changePercent {
100
+ Text(String(format: "%+.2f%%", change))
101
+ .font(.system(size: 9, weight: .semibold))
102
+ .foregroundStyle(change >= 0 ? Color.green : Color.red)
103
+ .lineLimit(1)
104
+ }
105
+ }
106
+ }
107
+ .frame(maxWidth: .infinity, alignment: .leading)
108
+ .accessibilityElement(children: .combine)
109
+ .accessibilityLabel("\(quote?.name ?? symbol)، \(quote.map { formatPrice($0.price) } ?? "ناموجود") \(quote?.quoteLabel ?? "")")
110
+ }
111
+
112
+ private var footer: some View {
113
+ HStack(spacing: 4) {
114
+ Text(entry.usedOfflineCache ? "آفلاین · آخرین قیمت ذخیرهشده"
115
+ : entry.stale ? "داده قدیمی · غیرلحظهای"
116
+ : "آخرین نرخ منبع · غیرلحظهای")
117
+ .lineLimit(1).minimumScaleFactor(0.72)
118
+ Spacer(minLength: 0)
119
+ if family != .systemSmall {
120
+ Text(MarketDate.format(entry.fetchedAt))
121
+ .lineLimit(1)
122
+ }
123
+ }
124
+ .font(.system(size: 8))
125
+ .foregroundStyle(subdued)
126
+ }
127
+
128
+ private func formatPrice(_ value: Double) -> String {
129
+ value.formatted(.number.precision(.fractionLength(0...2)))
130
+ }
131
+}
ios/ChartNova/project.yml
new
+84
@@ -0,0 +1,84 @@
1
+name: ChartNova
2
+options:
3
+ createIntermediateGroups: true
4
+ deploymentTarget:
5
+ iOS: "17.0"
6
+settings:
7
+ base:
8
+ SWIFT_VERSION: "5.0"
9
+ IPHONEOS_DEPLOYMENT_TARGET: "17.0"
10
+ TARGETED_DEVICE_FAMILY: "1"
11
+ MARKETING_VERSION: "1.0.0"
12
+ CURRENT_PROJECT_VERSION: "1"
13
+ CODE_SIGN_STYLE: Automatic
14
+ DEVELOPMENT_ASSET_PATHS: ""
15
+targets:
16
+ ChartNova:
17
+ type: application
18
+ platform: iOS
19
+ sources:
20
+ - path: App
21
+ - path: Shared
22
+ - path: Resources/Assets.xcassets
23
+ info:
24
+ path: App/Info.plist
25
+ properties:
26
+ CFBundleDisplayName: ChartNova
27
+ CFBundleURLTypes:
28
+ - CFBundleURLName: ir.chartnova.ios
29
+ CFBundleURLSchemes: [chartnova]
30
+ UIUserInterfaceStyle: Automatic
31
+ entitlements:
32
+ path: App/ChartNova.entitlements
33
+ properties:
34
+ com.apple.security.application-groups: [group.ir.chartnova.widgets]
35
+ settings:
36
+ base:
37
+ PRODUCT_BUNDLE_IDENTIFIER: ir.chartnova.ios
38
+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
39
+ INFOPLIST_KEY_UIApplicationSceneManifest_Generation: "YES"
40
+ dependencies:
41
+ - target: ChartNovaWidgets
42
+ embed: true
43
+ ChartNovaWidgets:
44
+ type: app-extension
45
+ platform: iOS
46
+ sources:
47
+ - path: WidgetExtension
48
+ - path: Shared
49
+ info:
50
+ path: WidgetExtension/Info.plist
51
+ properties:
52
+ CFBundleDisplayName: ChartNova Widgets
53
+ NSExtension:
54
+ NSExtensionPointIdentifier: com.apple.widgetkit-extension
55
+ entitlements:
56
+ path: WidgetExtension/ChartNovaWidgets.entitlements
57
+ properties:
58
+ com.apple.security.application-groups: [group.ir.chartnova.widgets]
59
+ settings:
60
+ base:
61
+ PRODUCT_BUNDLE_IDENTIFIER: ir.chartnova.ios.widgets
62
+ SKIP_INSTALL: "YES"
63
+ APPLICATION_EXTENSION_API_ONLY: "YES"
64
+ ChartNovaTests:
65
+ type: bundle.unit-test
66
+ platform: iOS
67
+ sources:
68
+ - path: Tests
69
+ dependencies:
70
+ - target: ChartNova
71
+ settings:
72
+ base:
73
+ PRODUCT_BUNDLE_IDENTIFIER: ir.chartnova.ios.tests
74
+schemes:
75
+ ChartNova:
76
+ build:
77
+ targets:
78
+ ChartNova: all
79
+ ChartNovaWidgets: all
80
+ test:
81
+ targets:
82
+ - ChartNovaTests
83
+ run:
84
+ config: Debug
ios/ChartNova/verify-native.cjs
new
+17
@@ -0,0 +1,17 @@
1
+const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');const root=__dirname;
2
+const sw=['Shared/MarketModels.swift','Shared/WidgetSettings.swift','Shared/MarketAPI.swift','App/ChartNovaApp.swift','App/MarketViewModel.swift','App/MarketHomeView.swift','WidgetExtension/ChartNovaWidget.swift','WidgetExtension/ChartNovaWidgetView.swift','Tests/ChartNovaCoreTests.swift'];
3
+for(const rel of sw){const s=fs.readFileSync(path.join(root,rel),'utf8');assert(s.length>100,'empty source '+rel);assert(!s.includes('API_KEY')&&!s.includes('Bearer '),'secret leak '+rel);console.log('PASS source',rel,s.split('\n').length,'lines')}
4
+const y=fs.readFileSync(path.join(root,'project.yml'),'utf8');
5
+for(const item of ['ChartNovaWidgets:','ChartNovaTests:','NSExtensionPointIdentifier: com.apple.widgetkit-extension','group.ir.chartnova.widgets','type: app-extension','iOS: "17.0"'])assert(y.includes(item),'project spec '+item);
6
+console.log('PASS project targets, app group and iOS17 platform');
7
+const a=fs.readFileSync(path.join(root,'Resources/Assets.xcassets/AppIcon.appiconset/Contents.json'),'utf8'),asset=JSON.parse(a);
8
+const icon=path.join(root,'Resources/Assets.xcassets/AppIcon.appiconset/',asset.images[0].filename);
9
+assert(fs.statSync(icon).size>10000,'app icon too small');const header=fs.readFileSync(icon).subarray(0,24);assert.equal(header.readUInt32BE(16),1024);assert.equal(header.readUInt32BE(20),1024);console.log('PASS icon PNG 1024x1024');
10
+const web=fs.readFileSync(path.join(root,'Shared/MarketAPI.swift'),'utf8');
11
+assert(web.includes('https://app.chartnova.ir')&&web.includes('api/widget')&&web.includes('api/markets'));
12
+const ext=fs.readFileSync(path.join(root,'WidgetExtension/ChartNovaWidget.swift'),'utf8');
13
+for(const family of ['.systemSmall','.systemMedium','.systemLarge'])assert(ext.includes(family));
14
+assert(ext.includes('Timeline(entries:')&&ext.includes('WidgetQuoteCache.save'));
15
+console.log('PASS widget families, timeline and API wiring');
16
+const files=sw.length;
17
+console.log('PASS',files,'Swift files');