Repository Public
1// Generates the Swift alert catalogue and the test vectors from the backend's own TypeScript (read-only import).2import { writeFileSync } from 'node:fs';3const B = '/Users/simon-pierreboucher/Desktop/Cluster/projets/sp-wallet';4const W = '/Users/simon-pierreboucher/Desktop/Cluster/apple/SPWalletCore-wt/ops';5import { readFileSync } from 'node:fs';6const await0 = readFileSync(`${B}/packages/core/src/alert-catalog.ts`, 'utf8');7const cat = await import(`${B}/packages/core/src/alert-catalog.ts`);8const sh = await import(`${B}/services/api/src/quotes/shared.ts`);9const camel = (k: string) => k.split(/[._]/).map((p, i) => (i === 0 ? p : p[0]!.toUpperCase() + p.slice(1))).join('');10const q = (s: string) => JSON.stringify(s).replace(/\$/g, '$');11const defs = cat.ALERT_DEFS as any[];12let s = `// SP Wallet Core13// File: Sources/SPWalletCore/Domains/Ops/AlertCatalog.swift14// Description: The alert catalogue of the backend (packages/core/src/alert-catalog.ts): every alert kind with its group, default15// severity, default switch and FR/EN wording. GENERATED from the backend's own TypeScript (ALERT_DEFS, SAFE_PARAMS,16// VOCAB are read by a script, never typed by hand) — regenerate when the backend adds a kind; do not edit.17// A kind this file does not know decodes to \`.unknown(String)\` and is shown verbatim.18//19// Author: Simon-Pierre Boucher20// Contact: contact@spboucher.ai21import Foundation2223/** The kind of an alert. ${defs.length} kinds in the catalogue of production (branch v11); anything else is \`.unknown\`. */24public enum AlertKind: Sendable, Hashable, Codable, CustomStringConvertible {25${defs.map((d) => ` case ${camel(d.kind)}`).join('\n')}26 /** A kind added by a newer server: kept verbatim, never mapped to a known one. */27 case unknown(String)2829 public static let allKnown: [AlertKind] = [${defs.map((d) => `.${camel(d.kind)}`).join(', ')}]3031 public var rawValue: String {32 switch self {33${defs.map((d) => ` case .${camel(d.kind)}: ${q(d.kind)}`).join('\n')}34 case .unknown(let s): s35 }36 }37 public init(rawValue: String) { self = AlertCatalog.kindsByRawValue[rawValue] ?? .unknown(rawValue) }38 public init(from decoder: Decoder) throws { self.init(rawValue: try decoder.singleValueContainer().decode(String.self)) }39 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }40 public var description: String { rawValue }41 public var isKnown: Bool { if case .unknown = self { false } else { true } }42}4344extension AlertCatalog {45 static let kindsByRawValue: [String: AlertKind] = Dictionary(uniqueKeysWithValues: AlertKind.allKnown.map { ($0.rawValue, $0) })4647 /** Parameters that may appear on a lock screen and in a webhook without "details" (SAFE_PARAMS). */48 public static let safeParams: [String] = [${(cat.SAFE_PARAMS as string[]).map(q).join(', ')}]4950 /** Parameter values of the form \`@word\` are vocabulary, translated where the alert is shown (VOCAB): [fr, en]. */51 static let vocabulary: [String: [String]] = [52${Object.entries(vocabOf()).map(([k, v]) => ` ${q(k)}: [${q(v[0])}, ${q(v[1])}],`).join('\n')}53 ]5455 /** ALERT_DEFS, in the order of the backend. */56 public static let definitions: [AlertDefinition] = [57${defs.map((d) => ` AlertDefinition(kind: .${camel(d.kind)}, group: .${d.group}, severity: .${d.severity}, defaultOn: ${d.on}, fixed: ${!!d.fixed},58 title: [${q(d.title[0])}, ${q(d.title[1])}],59 body: [${q(d.body[0])}, ${q(d.body[1])}],60 priv: ${d.priv ? `[${q(d.priv[0])}, ${q(d.priv[1])}]` : 'nil'}),`).join('\n')}61 ]62}63`;64// VOCAB is not exported: recover it through renderAlert on a template that prints one parameter ({what} of security.policy_changed priv is "{what} : …")65function vocabOf(): Record<string, [string, string]> {66 const src = (await0).match(/const VOCAB[^=]*= \{([\s\S]*?)\n\};/)![1]!;67 const out: Record<string, [string, string]> = {};68 for (const m of src.matchAll(/([a-z_]+): \[('(?:[^'\\]|\\.)*'), ('(?:[^'\\]|\\.)*')\]/g)) out[m[1]!] = [eval(m[2]!), eval(m[3]!)];69 // cross-check every word through the exported renderer70 for (const [k, v] of Object.entries(out)) for (const [i, l] of (['fr', 'en'] as const).entries()) {71 const r = cat.renderAlert('conn.up', { name: `@${k}` }, l).body as string;72 if (!r.startsWith(v[i]!)) throw new Error(`vocab ${k} ${l}: ${r} vs ${v[i]}`);73 }74 return out;75}76writeFileSync(`${W}/Sources/SPWalletCore/Domains/Ops/AlertCatalog.swift`, s);7778// ---- vectors79const sample: Record<string, string | number | boolean | null> = { network: 'Base', symbol: 'USDC', amount: '25', toSymbol: 'ETH', to: 'Arbitrum One', reason: 'insufficient funds', what: '@swap', state: '@confirming', minutes: 45, agent: 'Momentum 1',80 count: 3, from: 'USDC', mode: '@paper', bars: 4, interval: '1h', name: '@market', hours: 12, account: 'HL main', side: '@buy', size: '0.5', instrument: 'hyperliquid:BTC', price: '65000.5', clientId: 'c-1', seconds: 60, pnl: '-12.5',81 positions: 2, scope: '@daily', label: 'iPhone', device: 'Safari · iPhone', ip: '203.0.113.7', seq: 42, detail: 'max leverage 3', loop: 'tracker', pct: 7.5, step: 2, steps: 3 };82const render: unknown[] = [];83for (const d of defs) for (const locale of ['fr', 'en'] as const) for (const detail of [true, false]) render.push({ kind: d.kind, locale, detail, params: sample, ...cat.renderAlert(d.kind, sample, locale, detail) });84render.push({ kind: 'transfer.confirmed', locale: 'en', detail: true, params: { network: 'Base' }, ...cat.renderAlert('transfer.confirmed', { network: 'Base' }, 'en', true) });85render.push({ kind: 'conn.down', locale: 'fr', detail: true, params: { name: '@nonexistent', minutes: null }, ...cat.renderAlert('conn.down', { name: '@nonexistent', minutes: null }, 'fr', true) });86render.push({ kind: 'not.a.kind', locale: 'en', detail: true, params: {}, ...cat.renderAlert('not.a.kind', {}, 'en', true) });87const subjects = [null, { type: 'agent', id: 'a1' }, { type: 'agent' }, { type: 'plan', id: 'p1' }, { type: 'account', id: 'x' }, { type: 'proposal', id: 'p' }, { type: 'deposit', id: 't' }, { type: 'none' }, { type: 'network', id: 'base' }];88const paths: unknown[] = [];89for (const k of ['transfer.confirmed', 'agent.stopped', 'deriv.halt', 'security.new_device', 'system.disk_low', 'not.a.kind']) for (const sub of subjects) paths.push({ kind: k, subject: sub, path: cat.alertPath(k, sub) });90writeFileSync(`${W}/Tests/SPWalletCoreTests/Vectors/ops-alert-catalog.json`, JSON.stringify({ source: 'packages/core/src/alert-catalog.ts (ALERT_DEFS, renderAlert, safeParams, alertPath), generated by /tmp/spw-ops-gen/gen.mts with node --experimental-strip-types; do not edit by hand',91 defs: defs.map((d) => ({ kind: d.kind, group: d.group, severity: d.severity, on: d.on, fixed: !!d.fixed })), safeParams: cat.SAFE_PARAMS, safe: cat.safeParams(sample), render, paths }, null, 1));9293const L = (...x: [string, string][]) => x;94const bids = L(['65000.5', '1.2'], ['65000', '3'], ['64999.5', '0.75']), asks = L(['65001', '0.4'], ['65001.5', '2'], ['65003', '9']);95const many = Array.from({ length: 14 }, (_, i) => [String(100 - i), String(i + 1)] as [string, string]), manyA = Array.from({ length: 14 }, (_, i) => [String(101 + i) + '.5', '0.' + (i + 1)] as [string, string]);96const cmp = [['65000.5', '65000.49'], ['9', '10'], ['0.10', '0.1'], ['-2', '1'], ['123456789012345678901234567890.1', '123456789012345678901234567890.2'], ['-1.5', '-1.25'], ['0', '0.0'], ['10', '9.999']].map(([a, b]) => ({ a, b, r: sh.cmpDec(a, b) }));97const apply = [98 { levels: bids, changes: L(['65000', '0'], ['64999', '5'], ['65000.5', '2']), side: 'bids', depth: 20 },99 { levels: L(['101', '1'], ['102', '1']), changes: L(['100.5', '2']), side: 'asks', depth: 2 },100 { levels: asks, changes: L(), side: 'asks', depth: 2 },101 { levels: many, changes: L(['100.5', '7'], ['95', '0']), side: 'bids', depth: 10 },102].map((x) => ({ ...x, out: sh.applyLevels(x.levels, x.changes, x.side, x.depth) }));103const rnd = [0, 0.25, 0.5, 1];104writeFileSync(`${W}/Tests/SPWalletCoreTests/Vectors/ops-quote-shared.json`, JSON.stringify({ source: 'services/api/src/quotes/shared.ts (crc32, bookChecksum, cmpDec, applyLevels, channelKey, backoffMs, CLOSE, HEARTBEAT_MS), generated by /tmp/spw-ops-gen/gen.mts; do not edit by hand',105 protocol: sh.QUOTE_PROTOCOL_VERSION, heartbeatMs: sh.HEARTBEAT_MS, close: sh.CLOSE, bookDepths: sh.BOOK_DEPTHS, candleIntervals: sh.CANDLE_INTERVALS, channelTypes: sh.CHANNEL_TYPES,106 crc32: ['123456789', '', '65000.5:1.2|65000:3;65001:0.4'].map((t) => ({ text: t, crc: sh.crc32(t) })),107 checksum: [{ bids, asks }, { bids: many, asks: manyA }, { bids: [], asks: [] }, { bids, asks: [] }].map((x) => ({ ...x, checksum: sh.bookChecksum(x.bids, x.asks) })),108 cmp, apply,109 channelKey: [{ type: 'quote', id: 'hyperliquid:BTC' }, { type: 'book', id: 'hyperliquid:BTC' }, { type: 'book', id: 'dydx:BTC-USD', depth: 5 }, { type: 'candle', id: 'spot:BTC' }, { type: 'candle', id: 'spot:BTC', interval: '1h' }, { type: 'trades', id: 'gmx:BTC/USD [WBTC-USDC]' }, { type: 'status', id: '*' }].map((c) => ({ channel: c, key: sh.channelKey(c) })),110 backoff: [0, 1, 3, 5, 16, 20].flatMap((attempt) => rnd.map((r) => ({ attempt, random: r, ms: sh.backoffMs(attempt, 1000, 30000, () => r) }))) }, null, 1));111console.log('ok', defs.length);112