/* vitals.js — Apple Health ingestion (Health Auto Export → KuentaGYM). * * The phone runs a "REST API" automation in Health Auto Export (HAE) that POSTs its JSON export * to /api/vitals/ingest. This module is the whole of what happens to that payload: parse, fold * into per-day buckets, merge with what is already stored, prune. Nothing here touches the * filesystem or the network — server.js owns the file, this owns the arithmetic, which is what * makes it testable without a phone (see test/vitals.test.js). * * ── Why this is not just "append the samples" ─────────────────────────────────────────────── * * A five-minute automation re-sends overlapping windows: with Date Range = "Today" or the * default ("previous day + today so far") every sync carries the whole day again, so appending * would double every step count. With Date Range = "Since Last Sync" the windows are disjoint * and *replacing* would throw away everything but the last five minutes. The same receiver has to * survive both without knowing which one the phone is configured for, so the rule is chosen per * payload from the payload's own shape: * * dayAggregated() every datapoint sits exactly on midnight * → HAE already grouped by day ("Time Grouping: Days"), and a grouped day is a *total*: * a day total only ever replaces another one. Wait, "replaces" is wrong for the current * day, which legitimately grows all day long — and that is precisely why replacement is * right here: the newer, larger total is the better answer, and re-sending the same * number is a no-op. Idempotent by construction, no ledger needed. * * otherwise real timestamps (raw samples, or grouped by hour/minute/second) * → union: a sample is identified by its instant plus its numbers and seen once. A repeat * is skipped, a genuinely new sample is added. Overlapping and disjoint windows both * come out right, because "have I seen this exact sample" is the question that does not * depend on the window at all. * * The one configuration neither rule can fully rescue is grouping by *minutes* with an * overlapping window: the minute still in progress is re-sent with a larger value each time, so * it is a new sample by the union rule and its value is added twice. The error is bounded by one * partial minute of the cheapest metric (a handful of steps, a few hundredths of a kcal) and the * setup steps in docs/HEALTH.md say to group by Days. Being explicit about that beats a "smart" * rule that silently miscounts a whole day. * * ── What a stored document looks like ──────────────────────────────────────────────────────── * * Buckets are **per day, keyed by the day the phone wrote**, never by the server's own timezone: * HAE stamps each sample with the phone's local offset, so grouping by a server-local date would * slide every evening's steps into the next day for anyone not on UTC. The day key is therefore * taken straight from the payload's own date text. * * { * v: 1, updatedAt: 1699999999999, * last: { ts, metrics, points, duplicates, workouts, source }, * metrics: { * step_count: { * units: 'count', sources: ['iPhone'], * days: { '2026-05-01': { n: 288, lastTs: 1699999999999, * f: { qty: { sum, min, max, last, n } } } }, * seen: { '2026-05-01 13:05:00 +0200|qty:12': 1699999999999 } * } * }, * workouts: [ { name, start, end, durMin, fields: { activeEnergy: { qty, units } } } ] * } * * Numeric fields are kept generically (`f`) rather than decoded per metric, because a health * catalogue is wide and keeps growing: heart_rate carries Min/Avg/Max, blood_pressure carries * systolic/diastolic, sleep carries asleep/inBed/core/deep/rem — and a metric this code has never * heard of still lands in `f` under whatever HAE called it. Which field a *card* shows is a * presentation decision, and it lives in frontend/src/lib/vitals-view.js with the labels. That * split is deliberate: it means a metric added to HAE next year shows up without a server change. */ export const VITALS_VERSION = 1; /** Ledger lives 72 h: the longest overlap a sane automation cadence can span. */ export const LEDGER_MS = 72 * 3600 * 1000; /** Days kept per metric. A little over a year, so "same day last year" still exists. */ export const RETENTION_DAYS = 400; export const MAX_WORKOUTS = 300; /** Sources remembered per metric — decorative, but it answers "which watch sent this?" */ const MAX_SOURCES = 4; const MAX_LEDGER_KEYS = 20000; // hard ceiling; the time-based prune is the real bound export function emptyVitals() { return { v: VITALS_VERSION, updatedAt: 0, last: null, metrics: {}, workouts: [] }; } /** A stored document that is missing pieces (hand-edited, or written by an older version). */ export function normalizeDoc(doc) { const d = doc && typeof doc === 'object' && !Array.isArray(doc) ? doc : {}; const out = { v: VITALS_VERSION, updatedAt: Number(d.updatedAt) || 0, last: d.last && typeof d.last === 'object' ? d.last : null, metrics: {}, workouts: Array.isArray(d.workouts) ? d.workouts.filter(w => w && typeof w === 'object') : [] }; const metrics = d.metrics && typeof d.metrics === 'object' && !Array.isArray(d.metrics) ? d.metrics : {}; for (const [name, m] of Object.entries(metrics)) { if (!m || typeof m !== 'object') continue; const days = m.days && typeof m.days === 'object' && !Array.isArray(m.days) ? m.days : {}; out.metrics[name] = { units: typeof m.units === 'string' ? m.units : '', sources: Array.isArray(m.sources) ? m.sources.filter(s => typeof s === 'string').slice(0, MAX_SOURCES) : [], days, seen: m.seen && typeof m.seen === 'object' && !Array.isArray(m.seen) ? m.seen : {} }; } return out; } /* ---------- parsing ---------- */ // HAE writes "2021-12-24 00:04:00 +0800", or "2021-12-24 3:04:05 PM -0700" when the phone is on // a 12-hour clock — and that separator is U+202F (narrow no-break space), not a plain space, which // is exactly the kind of thing that turns into NaN three weeks later. Both are normalised below. const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{1,2}):(\d{2}):(\d{2})(?:[\s\u202f\u00a0]*([AaPp])\.?[Mm]\.?)?(?:[\s\u202f\u00a0]*([+-]\d{2}):?(\d{2})|Z)?$/; /** * Parse one HAE timestamp. * @returns {{ms:number, day:string, time:string, raw:string}|null} `day` is the date the phone * wrote (its own local day), `time` is "HH:MM:SS" in 24-hour form, `ms` an epoch instant. */ export function parseHaeDate(value) { if (typeof value !== 'string') return null; const raw = value.trim(); const m = DATE_RE.exec(raw); if (!m) return null; const [, y, mo, d, h, mi, s, ap, offH, offM] = m; let hour = Number(h); if (ap) { // 12 AM is 00, 12 PM is 12 — the two hours the naive modulo gets wrong. const pm = ap.toLowerCase() === 'p'; if (hour === 12) hour = pm ? 12 : 0; else if (pm) hour += 12; } if (hour > 23 || Number(mi) > 59 || Number(s) > 59) return null; const time = `${String(hour).padStart(2, '0')}:${mi}:${s}`; const day = `${y}-${mo}-${d}`; const offset = offH ? `${offH}:${offM || '00'}` : 'Z'; // no offset in the payload means UTC const ms = Date.parse(`${day}T${time}${offset}`); if (!Number.isFinite(ms)) return null; return { ms, day, time, raw }; } /** True when HAE grouped this datapoint onto a boundary rather than sampling it in real time. */ const isMidnight = t => t.time === '00:00:00'; // Fields on a datapoint that are not measurements. Everything else numeric is kept, so a metric // this file has never seen still stores its numbers instead of being dropped. const NON_VALUE_KEYS = new Set(['date', 'startDate', 'endDate', 'sleepStart', 'sleepEnd', 'inBedStart', 'inBedEnd', 'source', 'Source', 'value']); const num = v => (typeof v === 'number' && Number.isFinite(v) ? v : null); /** The numeric measurements on one datapoint, keyed exactly as HAE named them. */ export function fieldsOf(point) { const out = {}; for (const [k, v] of Object.entries(point)) { if (NON_VALUE_KEYS.has(k)) continue; const n = num(v); if (n != null) out[k] = n; } return out; } /** The instant of a datapoint: metrics carry `date`, sleep carries `sleepStart`/`startDate`. */ function instantOf(point) { for (const k of ['date', 'sleepStart', 'startDate', 'inBedStart']) { const t = parseHaeDate(point[k]); if (t) return t; } return null; } const str = v => (typeof v === 'string' ? v : ''); /** * Validate and normalise an HAE export body into what mergeVitals() expects. * * Version 2 wraps everything in `data`; the older flat shape puts the arrays at the top level and * is accepted too, since it costs one line and a user pasting an old export should not get a * blank page. A metric with `data: null` is normal (HAE sends the metric because it is selected * but has no samples) and is dropped here rather than stored as an empty day. * * @throws {Error} with `.code` of 'shape' (not an export at all) or 'empty' (an export with * nothing in it) — server.js turns both into a 400 that names the problem. */ export function parsePayload(body) { if (!body || typeof body !== 'object' || Array.isArray(body)) throw err('shape'); const data = body.data && typeof body.data === 'object' && !Array.isArray(body.data) ? body.data : body; const rawMetrics = Array.isArray(data.metrics) ? data.metrics : []; const rawWorkouts = Array.isArray(data.workouts) ? data.workouts : []; if (!rawMetrics.length && !rawWorkouts.length && !('metrics' in data) && !('workouts' in data)) throw err('shape'); const metrics = []; for (const m of rawMetrics) { if (!m || typeof m !== 'object') continue; const name = str(m.name).trim(); if (!name) continue; const points = []; for (const p of Array.isArray(m.data) ? m.data : []) { if (!p || typeof p !== 'object') continue; const at = instantOf(p); if (!at) continue; // a datapoint with no readable date is unusable const fields = fieldsOf(p); if (!Object.keys(fields).length) continue; // ...and so is one with no numbers points.push({ at, fields, source: str(p.source) || str(p.Source) }); } metrics.push({ name, units: str(m.units), points }); } const workouts = []; for (const w of rawWorkouts) { if (!w || typeof w !== 'object') continue; const name = str(w.name).trim(); const start = parseHaeDate(w.start); if (!name || !start) continue; const end = parseHaeDate(w.end); const fields = {}; for (const [k, v] of Object.entries(w)) { if (['name', 'start', 'end', 'route', 'heartRateData', 'heartRateRecovery'].includes(k)) continue; const q = v && typeof v === 'object' && !Array.isArray(v) ? num(v.qty) : num(v); if (q == null) continue; fields[k] = { qty: q, units: v && typeof v === 'object' ? str(v.units) : '' }; } const mins = end ? Math.round((end.ms - start.ms) / 60000) : null; workouts.push({ name, start: start.ms, end: end ? end.ms : null, day: start.day, durMin: mins != null && mins >= 0 ? mins : null, avgHr: hrAvg(w.heartRateData) ?? fields.heartRate?.qty ?? null, maxHr: hrMax(w.heartRateData) ?? null, fields }); } if (!metrics.length && !workouts.length) throw err('empty'); return { metrics, workouts }; } const err = code => Object.assign(new Error(code), { code }); /** Average of HAE's per-second/minute workout heart-rate samples. */ function hrAvg(samples) { if (!Array.isArray(samples) || !samples.length) return null; const vals = samples.map(s => num(s?.Avg) ?? num(s?.qty)).filter(v => v != null); if (!vals.length) return null; return Math.round((vals.reduce((a, b) => a + b, 0) / vals.length) * 10) / 10; } function hrMax(samples) { if (!Array.isArray(samples) || !samples.length) return null; const vals = samples.map(s => num(s?.Max) ?? num(s?.qty)).filter(v => v != null); return vals.length ? Math.max(...vals) : null; } /* ---------- merging ---------- */ /** Does this metric payload look like HAE's own day-by-day grouping? */ function dayGrouped(points) { return points.length > 0 && points.every(p => isMidnight(p.at)); } const dayKeyOk = k => /^\d{4}-\d{2}-\d{2}$/.test(k); function addFields(bucket, fields) { for (const [k, v] of Object.entries(fields)) { const f = bucket.f[k] || (bucket.f[k] = { n: 0, sum: 0, min: v, max: v, last: v }); f.n++; f.sum += v; if (v < f.min) f.min = v; if (v > f.max) f.max = v; f.last = v; } bucket.n++; } const bucketFrom = (fields, ts) => { const b = { n: 0, lastTs: ts, f: {} }; addFields(b, fields); return b; }; /** * Fold one parsed payload into a stored document. Pure: the input document is not modified. * * @returns {{doc:object, stats:{metrics:number, points:number, duplicates:number, workouts:number}}} */ export function mergeVitals(doc, payload, now = Date.now()) { const out = normalizeDoc(doc); const stats = { metrics: 0, points: 0, duplicates: 0, workouts: 0 }; for (const m of payload.metrics) { if (!m.points.length) continue; stats.metrics++; const cur = out.metrics[m.name] || { units: '', sources: [], days: {}, seen: {} }; if (m.units) cur.units = m.units; const replace = dayGrouped(m.points); // The ledger is only consulted by the union path, and only for instants recent enough to be // re-sent by the next automation run — anything older is pruned and can no longer be a repeat. pruneLedger(cur.seen, now); for (const p of m.points) { const key = p.at.day; if (!dayKeyOk(key)) continue; if (p.source && !cur.sources.includes(p.source)) { cur.sources = [p.source, ...cur.sources].slice(0, MAX_SOURCES); } if (replace) { const prev = cur.days[key]; // Nothing to do when the phone re-sends the value we already have (the common case for // every run after the first). `f` is compared as a whole because a day total and a // once-a-day gauge both live in it. if (prev && prev.n === 1 && sameFields(prev.f, p.fields)) { stats.duplicates++; continue; } cur.days[key] = bucketFrom(p.fields, p.at.ms); stats.points++; continue; } const id = sampleId(p); if (cur.seen[id] != null) { stats.duplicates++; continue; } cur.seen[id] = p.at.ms; addFields(cur.days[key] || (cur.days[key] = { n: 0, lastTs: p.at.ms, f: {} }), p.fields); cur.days[key].lastTs = Math.max(cur.days[key].lastTs, p.at.ms); stats.points++; } pruneLedger(cur.seen, now, true); out.metrics[m.name] = cur; } if (payload.workouts.length) { const seen = new Set(out.workouts.map(w => wkey(w))); for (const w of payload.workouts) { const k = wkey(w); if (seen.has(k)) { stats.duplicates++; continue; } seen.add(k); out.workouts.push(w); stats.workouts++; } // Newest first, and the oldest are dropped: a wrist that records every walk produces // thousands of entries a year, and nobody scrolls past the last few hundred. out.workouts.sort((a, b) => b.start - a.start); if (out.workouts.length > MAX_WORKOUTS) out.workouts.length = MAX_WORKOUTS; } pruneDays(out, now); out.updatedAt = now; out.last = { ts: now, ...stats }; return { doc: out, stats }; } const wkey = w => `${w.name}|${w.start}|${w.end ?? ''}`; /** Same numbers as the stored bucket? `raw` is a payload's plain field map, `stored` a bucket's. */ function sameFields(stored, raw) { const ka = Object.keys(stored), kb = Object.keys(raw); if (ka.length !== kb.length) return false; return ka.every(k => raw[k] === stored[k].last); } /** A sample's identity: when it happened plus what it says. */ function sampleId(p) { const f = Object.keys(p.fields).sort().map(k => `${k}:${p.fields[k]}`).join(','); return `${p.at.raw}|${f}`; } function pruneLedger(seen, now, enforceCap = false) { for (const [k, ts] of Object.entries(seen)) if (now - ts > LEDGER_MS) delete seen[k]; if (!enforceCap) return; const keys = Object.keys(seen); if (keys.length <= MAX_LEDGER_KEYS) return; // Oldest first — a repeat can only be recent, so the tail is what may be given up. keys.sort((a, b) => seen[a] - seen[b]); for (const k of keys.slice(0, keys.length - MAX_LEDGER_KEYS)) delete seen[k]; } function pruneDays(doc, now) { const oldest = new Date(now - RETENTION_DAYS * 86400000).toISOString().slice(0, 10); for (const m of Object.values(doc.metrics)) { for (const day of Object.keys(m.days)) if (day < oldest) delete m.days[day]; } } /* ---------- reading ---------- */ /** * Project a stored document into the compact series the view renders, oldest day first. * Aggregates are per *field* — `qty.sum` for a counter, `Avg.last` for a rate — so the client * never has to know how HAE grouped things. */ export function vitalsSeries(doc, { days = 90, now = Date.now() } = {}) { const d = normalizeDoc(doc); // `days` counts calendar days *including today*, so `days: 1` is today alone. Day keys are the // phone's own local dates (see the header), which is why this is a plain string comparison // rather than an instant one: an evening sample in Manila and one in Lima each keep their own // day, and neither is dragged across a boundary by the server's timezone. const from = new Date(now - Math.max(0, days - 1) * 86400000).toISOString().slice(0, 10); const metrics = {}; for (const [name, m] of Object.entries(d.metrics)) { const out = []; for (const day of Object.keys(m.days).sort()) { if (day < from) continue; const b = m.days[day]; const f = {}; for (const [k, v] of Object.entries(b.f || {})) { f[k] = { n: v.n, sum: v.sum, min: v.min, max: v.max, last: v.last, avg: v.n ? v.sum / v.n : null }; } out.push({ day, n: b.n, lastTs: b.lastTs, f }); } if (out.length) metrics[name] = { units: m.units, sources: m.sources, days: out }; } return { updatedAt: d.updatedAt, last: d.last, metrics, workouts: d.workouts }; }