|
| 1 | +import { HDSModel } from './HDSModel.ts'; |
| 2 | +import { EuclidianDistanceEngine } from '../converters/EuclidianDistanceEngine.ts'; |
| 3 | +import type { ConverterPack, ObservationVector, ConversionResult, SourceBlock } from '../converters/types.ts'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Converters — Extension of HDSModel |
| 7 | + * |
| 8 | + * Lazy-loads converter packs from the model's base URL: |
| 9 | + * {modelBaseUrl}/converters/{itemKey}/pack-latest.json |
| 10 | + * |
| 11 | + * The main pack.json only contains the converter index (item keys + versions). |
| 12 | + * Full converter data (dimensions + methods) is fetched on first use and cached. |
| 13 | + * |
| 14 | + * All conversion methods are async (first call fetches, subsequent calls are instant). |
| 15 | + */ |
| 16 | +export class HDSModelConverters { |
| 17 | + #model: HDSModel; |
| 18 | + #engines: Record<string, EuclidianDistanceEngine> = {}; |
| 19 | + #pendingLoads: Record<string, Promise<EuclidianDistanceEngine>> = {}; |
| 20 | + #itemKeyByEventType: Record<string, string> = {}; |
| 21 | + |
| 22 | + constructor (model: HDSModel) { |
| 23 | + this.#model = model; |
| 24 | + } |
| 25 | + |
| 26 | + /** List available converter item keys (from the index, may not be loaded yet) */ |
| 27 | + get availableItemKeys (): string[] { |
| 28 | + const converters = this.#model.modelData.converters; |
| 29 | + return converters ? Object.keys(converters) : []; |
| 30 | + } |
| 31 | + |
| 32 | + /** List loaded converter item keys */ |
| 33 | + get loadedItemKeys (): string[] { |
| 34 | + return Object.keys(this.#engines); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Load a converter pack manually. |
| 39 | + * Bridges and apps can call this to register packs without fetching from URL. |
| 40 | + */ |
| 41 | + loadPack (pack: ConverterPack): void { |
| 42 | + if (pack.engine !== 'euclidian-distance') { |
| 43 | + throw new Error(`Unknown converter engine: "${pack.engine}". Only "euclidian-distance" is supported.`); |
| 44 | + } |
| 45 | + this.#engines[pack.itemKey] = new EuclidianDistanceEngine(pack); |
| 46 | + this.#itemKeyByEventType[pack.eventType] = pack.itemKey; |
| 47 | + } |
| 48 | + |
| 49 | + /** Get a loaded engine (returns undefined if not yet loaded) */ |
| 50 | + getEngine (itemKey: string): EuclidianDistanceEngine | undefined { |
| 51 | + return this.#engines[itemKey]; |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Ensure a converter engine is loaded for the given item key. |
| 56 | + * Fetches pack-latest.json on first call, returns cached engine on subsequent calls. |
| 57 | + */ |
| 58 | + async ensureEngine (itemKey: string): Promise<EuclidianDistanceEngine> { |
| 59 | + if (this.#engines[itemKey]) return this.#engines[itemKey]; |
| 60 | + if (this.#pendingLoads[itemKey]) return this.#pendingLoads[itemKey]; |
| 61 | + |
| 62 | + this.#pendingLoads[itemKey] = this.#fetchAndLoadPack(itemKey); |
| 63 | + try { |
| 64 | + const engine = await this.#pendingLoads[itemKey]; |
| 65 | + return engine; |
| 66 | + } finally { |
| 67 | + delete this.#pendingLoads[itemKey]; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Convert a source method observation into a Pryv event structure. |
| 73 | + * |
| 74 | + * @param itemKey - converter item key (e.g. 'cervical-fluid', 'mood') |
| 75 | + * @param sourceMethod - source method id (e.g. 'mira', 'appleHealth') |
| 76 | + * @param dataFromSource - raw observation from the source method |
| 77 | + * @param modelVersion - version of the model definition used (default: engine's version) |
| 78 | + * @returns Pryv event-like object with type, streamIds, content |
| 79 | + */ |
| 80 | + async convertMethodToEvent (itemKey: string, sourceMethod: string, dataFromSource: any, modelVersion?: string): Promise<any> { |
| 81 | + const engine = await this.ensureEngine(itemKey); |
| 82 | + const itemDef = this.#getItemDef(itemKey); |
| 83 | + |
| 84 | + const vector = engine.toVector(sourceMethod, dataFromSource); |
| 85 | + |
| 86 | + const source: SourceBlock = { |
| 87 | + key: sourceMethod, |
| 88 | + sourceData: dataFromSource, |
| 89 | + engineVersion: engine.converterVersion, |
| 90 | + modelVersion: modelVersion ?? engine.converterVersion, |
| 91 | + }; |
| 92 | + |
| 93 | + return { |
| 94 | + type: engine.eventType, |
| 95 | + streamIds: [itemDef.streamId], |
| 96 | + content: { |
| 97 | + data: vector, |
| 98 | + source, |
| 99 | + }, |
| 100 | + }; |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * Convert a stored event to a target method observation. |
| 105 | + * |
| 106 | + * @param event - Pryv event with content.data (the N-D vector) |
| 107 | + * @param targetMethod - target method id |
| 108 | + * @returns { data, matchDistance } |
| 109 | + */ |
| 110 | + async convertEventToMethod (event: any, targetMethod: string): Promise<ConversionResult> { |
| 111 | + const itemKey = await this.#findItemKeyForEvent(event); |
| 112 | + const engine = await this.ensureEngine(itemKey); |
| 113 | + |
| 114 | + const vector: ObservationVector = event.content?.data; |
| 115 | + if (!vector || typeof vector !== 'object') { |
| 116 | + throw new Error(`Event content.data is not a valid vector: ${JSON.stringify(event.content)}`); |
| 117 | + } |
| 118 | + |
| 119 | + return engine.fromVector(targetMethod, vector); |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Convert directly between two methods. |
| 124 | + * |
| 125 | + * @param itemKey - converter item key |
| 126 | + * @param sourceMethod - source method id |
| 127 | + * @param targetMethod - target method id |
| 128 | + * @param data - observation in the source method |
| 129 | + * @returns { data, matchDistance } |
| 130 | + */ |
| 131 | + async convertMethodToMethod (itemKey: string, sourceMethod: string, targetMethod: string, data: any): Promise<ConversionResult> { |
| 132 | + const engine = await this.ensureEngine(itemKey); |
| 133 | + return engine.convertMethodToMethod(sourceMethod, targetMethod, data); |
| 134 | + } |
| 135 | + |
| 136 | + // ── Private helpers ───────────────────────────────────────────────────── |
| 137 | + |
| 138 | + async #fetchAndLoadPack (itemKey: string): Promise<EuclidianDistanceEngine> { |
| 139 | + // Check the converter index exists |
| 140 | + const converters = this.#model.modelData.converters; |
| 141 | + if (!converters?.[itemKey]) { |
| 142 | + throw new Error(`Unknown converter item key: "${itemKey}". Available: [${this.availableItemKeys.join(', ')}]`); |
| 143 | + } |
| 144 | + |
| 145 | + // Derive URL from model base URL |
| 146 | + const modelUrl = this.#model.modelUrl; |
| 147 | + const baseUrl = modelUrl.substring(0, modelUrl.lastIndexOf('/') + 1); |
| 148 | + const packUrl = `${baseUrl}converters/${itemKey}/pack-latest.json`; |
| 149 | + |
| 150 | + const response = await fetch(packUrl); |
| 151 | + if (!response.ok) { |
| 152 | + throw new Error(`Failed to fetch converter pack: ${packUrl} (${response.status})`); |
| 153 | + } |
| 154 | + const pack: ConverterPack = await response.json(); |
| 155 | + |
| 156 | + if (pack.engine !== 'euclidian-distance') { |
| 157 | + throw new Error(`Unknown converter engine: "${pack.engine}" in pack for "${itemKey}"`); |
| 158 | + } |
| 159 | + |
| 160 | + const engine = new EuclidianDistanceEngine(pack); |
| 161 | + this.#engines[itemKey] = engine; |
| 162 | + this.#itemKeyByEventType[engine.eventType] = itemKey; |
| 163 | + return engine; |
| 164 | + } |
| 165 | + |
| 166 | + #getItemDef (itemKey: string): any { |
| 167 | + const items = this.#model.modelData.items; |
| 168 | + for (const [_key, item] of Object.entries(items) as [string, any][]) { |
| 169 | + const ce = item['converter-engine']; |
| 170 | + if (ce && ce.models === itemKey) { |
| 171 | + return item; |
| 172 | + } |
| 173 | + } |
| 174 | + throw new Error(`No itemDef found with converter-engine.models="${itemKey}"`); |
| 175 | + } |
| 176 | + |
| 177 | + async #findItemKeyForEvent (event: any): Promise<string> { |
| 178 | + const eventType = event.type; |
| 179 | + |
| 180 | + // Check already-loaded engines |
| 181 | + const cached = this.#itemKeyByEventType[eventType]; |
| 182 | + if (cached) return cached; |
| 183 | + |
| 184 | + // Check itemDefs for a matching eventType with converter-engine |
| 185 | + const items = this.#model.modelData.items; |
| 186 | + for (const [_key, item] of Object.entries(items) as [string, any][]) { |
| 187 | + if (item.eventType === eventType && item['converter-engine']) { |
| 188 | + const itemKey = item['converter-engine'].models; |
| 189 | + await this.ensureEngine(itemKey); |
| 190 | + return itemKey; |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + throw new Error(`No converter found for event type: "${eventType}"`); |
| 195 | + } |
| 196 | +} |
0 commit comments