Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix(import): the parsers stop trusting the file and the Hevy API

Boris 'B' Kurktchiev0b3c9dbb6232
diff --git a/frontend/src/lib/import-csv.hostile.test.js b/frontend/src/lib/import-csv.hostile.test.js
new file mode 100644
index 000000000..ce7678fa8
--- /dev/null
+++ b/frontend/src/lib/import-csv.hostile.test.js
@@ -0,0 +1,241 @@
+// What a file from someone else's app can do to the CSV / Apple Health importer. An export is the
+// one input the person did not write and cannot read before handing it over, so every cell is
+// treated as hostile here: wrong types, impossible dates, prototype names in the lookup columns,
+// absurd sizes, files that are not exports at all. Two rules are under test — the parser's own,
+// that a bad row is skipped and counted rather than thrown on, and that nothing leaves parseImport
+// the rest of the app cannot render — plus the merge rule that an import adds and never overwrites.
+import { describe, expect, it } from 'vitest'
+import { parseImport, parseWhen, mergeImport } from './import-csv.js'
+import { EXIDX } from './exercises.js'
+
+const BODY_PARTS = new Set(['chest', 'back', 'shoulders', 'upper arms', 'lower arms', 'upper legs', 'lower legs', 'waist', 'cardio', 'neck'])
+const kg = { unit: 'kg' }
+const FITNOTES = 'Date,Exercise,Category,Weight,Weight Unit,Reps,Distance,Distance Unit,Time,Comment'
+// One FitNotes row; "Zorb Twirl" matches nothing in the catalogue, so it always becomes a custom.
+const row = (o = {}) => [o.date ?? '2024-03-07', o.ex ?? 'Zorb Twirl', o.cat ?? '', o.w ?? '', o.u ?? '', o.r ?? '', o.dist ?? '', o.du ?? '', o.time ?? '', o.note ?? ''].join(',')
+const csv = (...rows) => [FITNOTES, ...rows].join('\n')
+const health = (...recs) => '<?xml version="1.0"?><HealthData>' + recs.map(r =>
+ `<Record type="HKQuantityTypeIdentifierBodyMass" unit="${r.unit ?? 'kg'}" value="${r.value}" startDate="${r.date} 08:00:00 +0000"/>`).join('') + '</HealthData>'
+
+describe('lookup columns that spell a prototype property', () => {
+ it('a category of __proto__ or constructor still yields a real body part', () => {
+ for (const cat of ['__proto__', 'constructor']) {
+ const p = parseImport(csv(row({ cat, w: 50, u: 'kg', r: 5 })), kg)
+ expect(p.error).toBeUndefined()
+ expect(p.customEx).toHaveLength(1)
+ const bp = p.customEx[0].bp
+ expect(typeof bp, `category "${cat}" gave bp ${String(bp)}`).toBe('string')
+ expect(BODY_PARTS.has(bp)).toBe(true)
+ }
+ })
+
+ it('a distance unit of __proto__ does not turn the speed into NaN', () => {
+ const p = parseImport(csv(row({ ex: 'Zorb Jog', dist: 5, du: '__proto__', time: '30:00' })), kg)
+ const set = p.workouts[0].entries[0].sets[0]
+ expect(set.min).toBe(30)
+ expect(Number.isFinite(set.speed), `speed ${set.speed}`).toBe(true)
+ })
+})
+
+describe('Apple Health records that are not a weight', () => {
+ it('drops a record whose value is not a positive number instead of storing NaN or 0', () => {
+ const p = parseImport(health({ value: '.', date: '2024-03-07' }, { value: '0', date: '2024-03-08' }, { value: '80.5', date: '2024-03-09' }), kg)
+ expect(p.kind).toBe('bodyweight')
+ expect(p.bodyweight.map(b => b.w)).toEqual([80.5])
+ })
+
+ it('a file of nothing but junk values is refused rather than imported empty', () => {
+ expect(parseImport(health({ value: '.', date: '2024-03-07' }), kg).error).toBe('unrecognised')
+ })
+
+ it('a record without a unit follows the profile; lb is converted', () => {
+ const p = parseImport(health({ value: '176.4', unit: 'lb', date: '2024-03-07' }), kg)
+ expect(p.converted).toBe(true)
+ expect(p.bodyweight[0].w).toBe(80)
+ })
+})
+
+describe('dates the calendar does not have', () => {
+ it('garbage in the date column skips the row', () => {
+ const p = parseImport(csv(
+ row({ date: 'yesterday', w: 50, u: 'kg', r: 5 }),
+ row({ date: '', w: 50, u: 'kg', r: 5 }),
+ row({ date: '2024-03-07', w: 50, u: 'kg', r: 5 }),
+ ), kg)
+ expect(p.workouts).toHaveLength(1)
+ expect(p.skipped).toBe(2)
+ })
+})
+
+describe('numbers that are not numbers', () => {
+ const one = o => parseImport(csv(row(o)), kg)
+
+ it('text, NaN and Infinity read as 0, and a row with nothing measured is skipped', () => {
+ for (const w of ['abc', 'NaN', 'Infinity', '-Infinity', '', ' ', '0x10']) {
+ const p = one({ w, u: 'kg' })
+ expect(p.workouts, `weight "${w}"`).toHaveLength(0)
+ expect(p.skipped).toBe(1)
+ }
+ })
+
+ it('a decimal comma is read as a decimal point', () => {
+ expect(one({ w: '"52,5"', u: 'kg', r: 5 }).workouts[0].entries[0].sets[0].w).toBe(52.5)
+ })
+
+ it('reps: a billion is kept, text is 0', () => {
+ expect(one({ w: 50, u: 'kg', r: '1e9' }).workouts[0].entries[0].sets[0].r).toBe(1e9)
+ expect(one({ w: 50, u: 'kg', r: 'ten' }).workouts[0].entries[0].sets[0].r).toBe(0)
+ })
+
+ it('an unknown weight unit is read as the profile unit; a mixed file converts per row', () => {
+ const p = one({ w: 50, u: 'stones', r: 5 })
+ expect(p.fileUnit).toBe('')
+ expect(p.converted).toBe(false)
+ const mixed = parseImport(csv(row({ w: 50, u: 'kg', r: 5 }), row({ date: '2024-03-08', w: 100, u: 'lbs', r: 5 })), kg)
+ expect(mixed.mixedUnits).toBe(true)
+ expect(mixed.workouts[1].entries[0].sets[0].w).toBe(45.4)
+ })
+})
+
+describe('sizes nobody exports', () => {
+ it('a thousand rows, each a different unknown exercise, is one workout with a thousand entries', () => {
+ const rows = Array.from({ length: 1000 }, (_, i) => row({ ex: `Zorb Move ${i}`, w: 50, u: 'kg', r: 5 }))
+ const t0 = performance.now()
+ const p = parseImport(csv(...rows), kg)
+ expect(performance.now() - t0).toBeLessThan(5000)
+ expect(p.workouts).toHaveLength(1)
+ expect(p.workouts[0].entries).toHaveLength(1000)
+ expect(p.customEx).toHaveLength(1000)
+ expect(p.created).toBe(1000)
+ })
+
+ it('a thousand sets of one exercise on one day stay one entry', () => {
+ const p = parseImport(csv(...Array.from({ length: 1000 }, () => row({ w: 50, u: 'kg', r: 5 }))), kg)
+ expect(p.workouts[0].entries).toHaveLength(1)
+ expect(p.workouts[0].entries[0].sets).toHaveLength(1000)
+ expect(p.sets).toBe(1000)
+ })
+
+ it('a thousand days become a thousand workouts, oldest first', () => {
+ const rows = Array.from({ length: 1000 }, (_, i) => row({ date: new Date(Date.UTC(2020, 0, 1 + i)).toISOString().slice(0, 10), w: 50, u: 'kg', r: 5 }))
+ const p = parseImport(csv(...rows), kg)
+ expect(p.workouts).toHaveLength(1000)
+ expect(p.from).toBe('2020-01-01')
+ expect(p.workouts.map(w => w.d)).toEqual([...p.workouts.map(w => w.d)].sort())
+ })
+})
+
+describe('files that are not an export at all', () => {
+ it('an openGym backup dropped on the wrong button is refused', () => {
+ expect(parseImport('{"workouts":"hello","routines":"world"}', kg).error).toBe('empty')
+ expect(parseImport(JSON.stringify({ workouts: 'hello', routines: [] }, null, 2), kg).error).toBe('unrecognised')
+ })
+
+ it('a header with no rows, or nothing at all, is empty; whitespace lines are refused', () => {
+ expect(parseImport(FITNOTES, kg).error).toBe('empty')
+ expect(parseImport(FITNOTES + '\n\n\n', kg).error).toBe('empty')
+ expect(parseImport('', kg).error).toBe('empty')
+ expect(parseImport(' \n \n', kg).error).toBeTruthy()
+ })
+
+ it('a recognised header whose rows are all junk parses to nothing, without an error', () => {
+ const p = parseImport(csv(row({ date: 'x' }), ',,,,,,,,,', 'a,b,c'), kg)
+ expect(p.error).toBeUndefined()
+ expect(p.workouts).toEqual([])
+ expect(p.from).toBeNull()
+ })
+
+ it('rows shorter or longer than the header do not throw', () => {
+ const p = parseImport(csv('2024-03-07,Zorb Twirl', '2024-03-08,Zorb Twirl,,50,kg,5,,,,,extra,cells,here'), kg)
+ expect(p.workouts).toHaveLength(1) // the short row has nothing measured; the long one is fine
+ })
+
+ it('an HTML page or an XML that is not Apple Health is refused', () => {
+ expect(parseImport('<!doctype html>\n<html>\n<body>Sign in</body>\n</html>', kg).error).toBeTruthy()
+ expect(parseImport('<?xml version="1.0"?>\n<root>\n<item/>\n</root>', kg).error).toBeTruthy()
+ })
+
+ it('never throws, whatever the bytes', () => {
+ const nasty = [
+ '"', '"""', '"unterminated', ',,,\n,,,', '\u0000\u0001\u0002', '', 'Date,Exercise\n', '‮abc',
+ '🏋️‍♂️,💪\n🤸,🧘', 'Date,Exercise\n' + '\r'.repeat(1000), 'a'.repeat(200_000), ','.repeat(10_000), '\n'.repeat(10_000),
+ 'Date,Exercise,Weight\n' + '2024-03-07,"a,b",c\n'.repeat(500), 'Exercise,Date\n"' + 'x'.repeat(100_000) + ',2024-03-07',
+ 'Date,Exercise,Weight\n2024-03-07,__proto__,5\n2024-03-07,constructor,5\n2024-03-07,toString,5',
+ ]
+ for (const text of nasty) {
+ let out
+ expect(() => { out = parseImport(text, kg) }, JSON.stringify(text.slice(0, 20))).not.toThrow()
+ expect(out && typeof out === 'object').toBe(true)
+ if (!out.error) expect(Array.isArray(out.workouts) || Array.isArray(out.bodyweight)).toBe(true)
+ }
+ })
+})
+
+describe('mergeImport adds and never overwrites', () => {
+ const state = () => ({
+ unit: 'kg',
+ workouts: [{ id: 'mine', d: '2024-03-07', name: 'Mine', entries: [{ id: '0025', sets: [{ w: 100, r: 5, done: true }] }] }],
+ bodyweight: [{ d: '2024-03-07', w: 80, t: 1 }],
+ routines: [{ id: 'r1', name: 'Push', ex: [{ id: '0025', sets: 3, reps: 5, weight: 100 }] }],
+ customEx: [{ id: 'cu1', n: 'grip trainer', bp: 'lower arms', custom: true, eq: 'custom', tg: '', desc: '' }],
+ exWeights: { '0025': { w: 100, d: '2024-03-07', t: 1 } },
+ })
+
+ it('a day that is already here is left alone; routines and existing customs are untouched', () => {
+ const S = state()
+ const p = parseImport(csv(
+ row({ date: '2024-03-07', ex: 'Bench Press', w: 1, u: 'kg', r: 1 }),
+ row({ date: '2024-03-08', ex: 'Grip Trainer', w: 20, u: 'kg', r: 12 }),
+ ), kg)
+ expect(mergeImport(S, p)).toEqual({ added: 1, skipped: 1 })
+ expect(S.workouts.map(w => w.d)).toEqual(['2024-03-07', '2024-03-08'])
+ expect(S.workouts[0].name).toBe('Mine')
+ expect(S.routines).toEqual(state().routines)
+ expect(S.customEx).toEqual(state().customEx) // "Grip Trainer" reused cu1, nothing appended
+ expect(S.workouts[1].entries[0].id).toBe('cu1')
+ expect(S.exWeights['0025']).toEqual(state().exWeights['0025']) // the skipped day seeds nothing
+ expect(S.exWeights.cu1).toMatchObject({ w: 20, d: '2024-03-08' })
+ })
+
+ it('a custom exercise from a file can never shadow a built-in', () => {
+ const p = parseImport(csv(row({ date: '2024-03-08', ex: 'Zorb Twirl', w: 50, u: 'kg', r: 5 }), row({ date: '2024-03-08', ex: 'Barbell Bench Press', w: 50, u: 'kg', r: 5 })), kg)
+ expect(p.matched).toBe(1)
+ expect(p.customEx).toHaveLength(1)
+ expect(p.customEx.every(c => c.id.startsWith('im') && !EXIDX[c.id])).toBe(true)
+ const S = state()
+ mergeImport(S, p)
+ expect(S.customEx.map(c => c.n)).toEqual(['grip trainer', 'zorb twirl'])
+ expect(EXIDX['0025'].custom).toBeFalsy()
+ })
+
+ it('the merged shape is what the rest of the app reads', () => {
+ const S = state()
+ const p = parseImport(csv(
+ row({ date: '2024-03-08', ex: 'Zorb Twirl', w: 50, u: 'kg', r: 5 }),
+ row({ date: '2024-03-09', ex: 'Zorb Jog', dist: 5, du: 'km', time: '30:00' }),
+ ), kg)
+ mergeImport(S, p)
+ expect(S.workouts).toHaveLength(3)
+ for (const w of S.workouts) {
+ expect(typeof w.id).toBe('string')
+ expect(typeof w.d).toBe('string')
+ expect(typeof w.name).toBe('string')
+ expect(Array.isArray(w.entries)).toBe(true)
+ for (const e of w.entries) {
+ expect(typeof e.id).toBe('string')
+ expect(Array.isArray(e.sets)).toBe(true)
+ expect(e.sets.length).toBeGreaterThan(0)
+ }
+ }
+ expect(S.workouts[2].entries[0].sets[0]).toEqual({ min: 30, speed: 10, done: true })
+ })
+
+ it('weigh-ins: existing days win and the list stays sorted', () => {
+ const S = state()
+ const p = parseImport('Date,Weight (kg)\n2024-03-07,999\n2024-03-05,79\n2024-03-09,81', kg)
+ expect(p.kind).toBe('bodyweight')
+ expect(mergeImport(S, p)).toEqual({ added: 2, skipped: 1 })
+ expect(S.bodyweight.map(b => [b.d, b.w])).toEqual([['2024-03-05', 79], ['2024-03-07', 80], ['2024-03-09', 81]])
+ })
+
+})
diff --git a/frontend/src/lib/import-csv.js b/frontend/src/lib/import-csv.js
index 9315b920d..27dce72f0 100644
--- a/frontend/src/lib/import-csv.js
+++ b/frontend/src/lib/import-csv.js
@@ -301,13 +301,16 @@ export const bpFromName = name => {
}
// Categories the exporters use -> the dataset's body parts, for exercises we invent.
-const CATEGORY_BP = {
+// Indexed straight from a cell of the file, so it has no prototype: a plain object answers
+// "constructor" and "__proto__" with Object's own machinery, and a function or Object.prototype
+// would then ride into the store as an exercise's body part.
+const CATEGORY_BP = Object.assign(Object.create(null), {
chest: 'chest', back: 'back', lats: 'back', shoulders: 'shoulders', delts: 'shoulders',
legs: 'upper legs', quads: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs',
calves: 'lower legs', abs: 'waist', core: 'waist', obliques: 'waist',
arms: 'upper arms', biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
cardio: 'cardio', 'full body': 'upper legs', olympic: 'upper legs', neck: 'neck',
-}
+})
/* ----------------------------------------------------------- conversion --- */
@@ -392,7 +395,8 @@ function toMinutes(v) {
if (m || mm) return (m ? +m[1] * 60 : 0) + (mm ? +mm[1] : 0)
return Math.round(num(s) * 10) / 10
}
-const KM = { m: 0.001, km: 1, cm: 0.00001, in: 0.0000254, ft: 0.0003048, yd: 0.0009144, mi: 1.609344 }
+// No prototype for the same reason as CATEGORY_BP: the key is a cell from the file.
+const KM = Object.assign(Object.create(null), { m: 0.001, km: 1, cm: 0.00001, in: 0.0000254, ft: 0.0003048, yd: 0.0009144, mi: 1.609344 })
const toKm = (v, unit) => num(v) * (KM[String(unit || 'km').toLowerCase().trim()] ?? 1)
/* --------------------------------------------------------------- parse ---- */
@@ -616,7 +620,11 @@ export function parseBodyweight(text, { unit = 'kg' } = {}) {
const when = parseWhen(dt[1])
if (!when) continue
if (u) fileUnit = /lb/i.test(u[1]) ? 'lb' : 'kg'
- out.set(when.d, { w: parseFloat(val[1]), t: new Date(dt[1]).getTime() || null })
+ // `[\d.]+` lets a bare "." through, which parseFloat reads as NaN, and a zeroed record is
+ // no weigh-in either — the same gate the CSV branch below applies with `!w`.
+ const w = parseFloat(val[1])
+ if (!isFinite(w) || !w) continue
+ out.set(when.d, { w, t: new Date(dt[1]).getTime() || null })
}
} else {
const rows = parseCSV(s)
diff --git a/frontend/src/lib/import-hevy.hostile.test.js b/frontend/src/lib/import-hevy.hostile.test.js
new file mode 100644
index 000000000..9785ecf31
--- /dev/null
+++ b/frontend/src/lib/import-hevy.hostile.test.js
@@ -0,0 +1,212 @@
+// What a broken or hostile Hevy API response can do to the importer. The key is the user's, the
+// JSON is not: every field is read as if the server could put anything in it. Same two rules as
+// the CSV side — a bad item is skipped, and nothing reaches the store the app cannot render — and
+// the merge rule that routines are added or replace their own earlier copy, never anything else.
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { parseHevyWorkouts, parseHevyRoutines, parseHevyBodyweight, mergeHevyRoutines, fetchHevyPages, importHevyData } from './import-hevy.js'
+
+const BODY_PARTS = new Set(['chest', 'back', 'shoulders', 'upper arms', 'lower arms', 'upper legs', 'lower legs', 'waist', 'cardio', 'neck'])
+const kg = { unit: 'kg' }
+// 4E5257DE is in HEVY_ID_MAP (a lat pulldown); ZZZ1 / DEADBEEF are not, so they become customs.
+const T_LAT = { id: '4E5257DE', title: 'Lat Pulldown - Close Grip (Cable)', type: 'weight_reps', primary_muscle_group: 'lats' }
+const T_MINE = { id: 'DEADBEEF', title: 'My Invented Landmine Twist', type: 'weight_reps', primary_muscle_group: 'abdominals' }
+const set = (o = {}) => ({ type: 'normal', weight_kg: 50, reps: 5, distance_meters: null, duration_seconds: null, rpe: null, ...o })
+const lat = (...sets) => ({ exercise_template_id: '4E5257DE', title: 'Latzug', sets: sets.length ? sets : [set()] })
+const workout = (o = {}) => ({ id: 'w1', title: 'Push', start_time: '2024-03-07T12:00:00Z', end_time: '2024-03-07T13:00:00Z', exercises: [lat()], ...o })
+const routines = (r = {}, templates = [T_LAT, T_MINE]) => parseHevyRoutines([{ id: 'r1', title: 'Push', exercises: [lat()], ...r }], templates, kg)
+const reply = body => ({ ok: true, status: 200, headers: { get: () => null }, json: async () => body })
+
+describe('a template whose muscle group spells a prototype property', () => {
+ it('still gets a real body part', () => {
+ for (const g of ['__proto__', 'constructor']) {
+ const tpl = [{ id: 'ZZZ1', title: 'Zorb', primary_muscle_group: g }]
+ const p = parseHevyWorkouts([workout({ exercises: [{ exercise_template_id: 'ZZZ1', sets: [set()] }] })], tpl, kg)
+ expect(p.customEx).toHaveLength(1)
+ expect(typeof p.customEx[0].bp, `group "${g}" gave bp ${String(p.customEx[0].bp)}`).toBe('string')
+ expect(BODY_PARTS.has(p.customEx[0].bp)).toBe(true)
+ const r = parseHevyRoutines([{ id: 'r1', title: 'Push', exercises: [{ exercise_template_id: 'ZZZ1', sets: [set()] }] }], tpl, kg)
+ expect(typeof r.customEx[0].bp, `routine group "${g}"`).toBe('string')
+ }
+ })
+})
+
+describe('a workout title that is not text', () => {
+ it('never reaches the stored name — WorkoutRow renders it as a React child', () => {
+ for (const title of [{}, ['a', { b: 1 }], 12345, true, null, undefined]) {
+ const p = parseHevyWorkouts([workout({ title })], [T_LAT], kg)
+ expect(p.workouts).toHaveLength(1)
+ expect(typeof p.workouts[0].name, `title ${JSON.stringify(title)}`).toBe('string')
+ }
+ })
+
+ it('a later session on the same day lends its title only if it is text', () => {
+ const p = parseHevyWorkouts([workout({ title: '' }), workout({ id: 'w2', title: {}, start_time: '2024-03-07T18:00:00Z' })], [T_LAT], kg)
+ expect(p.workouts[0].name).toBe('Imported')
+ })
+})
+
+describe('paging through whatever the server sends', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('a string where the list should be is spread into characters, which then import as nothing', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => reply({ page_count: 1, workouts: 'hello' })))
+ const items = await fetchHevyPages('/v1/workouts', 'k', { resultKey: 'workouts' })
+ expect(items).toEqual(['h', 'e', 'l', 'l', 'o'])
+ const p = parseHevyWorkouts(items, [], kg)
+ expect(p.workouts).toEqual([])
+ expect(p.skipped).toBe(5)
+ })
+
+ it('a number or an object where the list should be, or a null body, throws — the sheet turns that into a toast', async () => {
+ for (const body of [{ page_count: 1, workouts: 5 }, { page_count: 1, workouts: { a: 1 } }, null]) {
+ vi.stubGlobal('fetch', vi.fn(async () => reply(body)))
+ await expect(fetchHevyPages('/v1/workouts', 'k', { resultKey: 'workouts' }), JSON.stringify(body)).rejects.toBeInstanceOf(TypeError)
+ }
+ })
+
+ it('page_count as text or NaN, and a page count that is a lie', async () => {
+ let calls = []
+ vi.stubGlobal('fetch', vi.fn(async url => { calls.push(new URL(url).searchParams.get('page')); return reply({ page_count: '3', workouts: calls.length < 3 ? [{}] : [] }) }))
+ expect(await fetchHevyPages('/v1/workouts', 'k', { resultKey: 'workouts' })).toHaveLength(2)
+ expect(calls).toEqual(['1', '2', '3'])
+ calls = []
+ vi.stubGlobal('fetch', vi.fn(async () => { calls.push(1); return reply({ page_count: NaN, workouts: [{}] }) }))
+ expect(await fetchHevyPages('/v1/workouts', 'k', { resultKey: 'workouts' })).toHaveLength(1)
+ expect(calls).toHaveLength(1)
+ })
+
+ it('a template that is not an object makes the whole import fail', async () => {
+ const pages = { exercise_templates: [null], workouts: [], routines: [], body_measurements: [] }
+ vi.stubGlobal('fetch', vi.fn(async url => { const u = String(url); const k = Object.keys(pages).find(k => u.includes('/v1/' + k)); return reply({ page_count: 1, [k]: pages[k] }) }))
+ await expect(importHevyData('k', kg)).rejects.toBeInstanceOf(TypeError)
+ })
+})
+
+describe('workout fields of the wrong type', () => {
+ const one = (...sets) => parseHevyWorkouts([workout({ exercises: [lat(...sets)] })], [T_LAT], kg)
+
+ it('a null workout throws (the sheet toasts); a string list of exercises or sets imports nothing', () => {
+ expect(() => parseHevyWorkouts([null], [T_LAT], kg)).toThrow(TypeError)
+ expect(parseHevyWorkouts([workout({ exercises: 'abc' })], [T_LAT], kg).workouts).toEqual([])
+ expect(parseHevyWorkouts([workout({ exercises: [{ exercise_template_id: '4E5257DE', sets: 'abc' }] })], [T_LAT], kg).workouts).toEqual([])
+ })
+
+ it('an exercise whose sets all have nothing measured leaves no empty entry behind, and is not counted as matched', () => {
+ const p = parseHevyWorkouts([workout({ exercises: [lat(set({ weight_kg: null, reps: null })), { exercise_template_id: 'DEADBEEF', sets: [set()] }] })], [T_LAT, T_MINE], kg)
+ expect(p.workouts).toHaveLength(1)
+ expect(p.workouts[0].entries).toHaveLength(1)
+ expect(p.workouts.flatMap(w => w.entries).filter(e => !e.sets.length)).toEqual([])
+ expect(p.matched).toBe(0)
+ expect(p.created).toBe(1)
+ })
+
+ it('an unmatched exercise that never landed a set is not invented, counted or listed', () => {
+ const none = { exercise_template_id: 'ZZZ1', sets: [set({ weight_kg: null, reps: null })] }
+ const tpl = [T_LAT, { id: 'ZZZ1', title: 'Zorb', primary_muscle_group: 'abs' }]
+ const p = parseHevyWorkouts([workout({ exercises: [lat(), none] })], tpl, kg)
+ expect([p.customEx, p.created, p.unmatchedNames, p.matched]).toEqual([[], 0, [], 1])
+ const r = parseHevyRoutines([{ id: 'r1', title: 'Push', exercises: [lat(), { exercise_template_id: 'ZZZ1', sets: [] }] }], tpl, kg)
+ expect([r.customEx, r.created, r.unmatchedNames, r.matched]).toEqual([[], 0, [], 1])
+ expect(r.routines[0].ex).toHaveLength(1)
+ // Same exercise with a set: invented once, counted once, listed once.
+ const q = parseHevyWorkouts([workout({ exercises: [lat(), { ...none, sets: [set()] }] })], tpl, kg)
+ expect([q.customEx.length, q.created, q.unmatchedNames]).toEqual([1, 1, ['Zorb']])
+ })
+
+ it('a session with nothing measured is not imported as an empty workout that blocks a real one later', () => {
+ expect(one(set({ weight_kg: 'abc', reps: 'abc' })).workouts).toEqual([])
+ expect(one(set({ weight_kg: null, reps: null })).workouts).toEqual([])
+ })
+
+ it('numbers that are not numbers', () => {
+ expect(one(set({ weight_kg: 'abc', reps: 'abc' })).sets).toBe(0)
+ expect(one(set({ weight_kg: '52.5', reps: '5' })).workouts[0].entries[0].sets[0]).toMatchObject({ w: 52.5, r: 5 })
+ expect(one(set({ rpe: 'abc' })).rpeSets).toBe(0)
+ expect(one(set({ rpe: -1 })).rpeSets).toBe(0)
+ expect(one(set({ rpe: 1e9 })).workouts[0].entries[0].sets[0].rpe).toBe(10)
+ expect(one(set({ weight_kg: null, reps: null, duration_seconds: 'abc', distance_meters: 'abc' })).sets).toBe(0)
+ const timed = one(set({ weight_kg: null, reps: null, duration_seconds: 600, distance_meters: 'abc' })).workouts[0].entries[0].sets[0]
+ expect(timed.min).toBe(10)
+ expect(Number.isFinite(timed.speed), `speed ${timed.speed}`).toBe(true)
+ })
+
+ it('a start that is not a timestamp skips the session — null included, which Date would read as 1970', () => {
+ for (const start_time of ['garbage', {}, [], null, 0, false, undefined, '', NaN]) {
+ const p = parseHevyWorkouts([workout({ start_time })], [T_LAT], kg)
+ expect(p.workouts, `start ${JSON.stringify(start_time)}`).toEqual([])
+ expect(p.skipped).toBe(1)
+ }
+ })
+
+ it('an end that is not a timestamp falls back to the start', () => {
+ for (const end_time of ['garbage', null, {}, undefined]) {
+ const p = parseHevyWorkouts([workout({ end_time })], [T_LAT], kg)
+ expect(p.workouts[0].end, `end ${JSON.stringify(end_time)}`).toBe(p.workouts[0].start)
+ }
+ })
+})
+
+describe('routine fields of the wrong type', () => {
+ it('a routine with no usable exercise is dropped, never saved with an empty list', () => {
+ expect(routines({ exercises: 'abc' }).routines).toEqual([])
+ expect(routines({ exercises: [] }).routines).toEqual([])
+ expect(routines({ exercises: [{ exercise_template_id: '4E5257DE', sets: [] }] }).routines).toEqual([])
+ expect(routines({ exercises: [{ exercise_template_id: '4E5257DE' }] }).routines).toEqual([])
+ expect(routines({ exercises: [{ sets: [set()] }] }).routines).toEqual([]) // no id, no title: nothing to resolve
+ })
+
+ it('a superset partner that never arrives is not a superset', () => {
+ const r = routines({ exercises: [
+ { exercise_template_id: '4E5257DE', superset_id: 0, sets: [set()] },
+ { exercise_template_id: 'DEADBEEF', sets: [set()] },
+ { exercise_template_id: '4E5257DE', superset_id: 0, sets: [set()] }, // same group, not adjacent
+ { exercise_template_id: 'DEADBEEF', superset_id: 'x', sets: [set()] },
+ { exercise_template_id: 'DEADBEEF', superset_id: 'x', sets: [set()] },
+ { exercise_template_id: 'DEADBEEF', superset_id: 'ghost', sets: [set()] },
+ ] }).routines[0]
+ expect(r.ex.map(e => e.sg === undefined)).toEqual([true, true, true, false, false, true])
+ expect(r.ex[3].sg).toBe(r.ex[4].sg)
+ })
+
+})
+
+describe('body measurements of the wrong type', () => {
+ it('skips what is not a dated positive weight', () => {
+ const p = parseHevyBodyweight([
+ { date: 12345, weight_kg: 80 }, { date: 'garbage', weight_kg: 80 }, { date: '2024-03-07', weight_kg: 'abc' },
+ { date: '2024-03-08', weight_kg: -1 }, { date: '2024-03-09', weight_kg: 0 }, { date: '2024-03-10', weight_kg: null },
+ { date: '2024-03-11T09:00:00Z', weight_kg: '80.5', created_at: 'garbage' }, {},
+ ], kg)
+ expect(p.bodyweight.map(b => [b.d, b.w])).toEqual([['2024-03-11', 80.5]])
+ expect(Number.isFinite(p.bodyweight[0].t)).toBe(true)
+ })
+
+ it('two readings on one day: the last one wins', () => {
+ const p = parseHevyBodyweight([{ date: '2024-03-07', weight_kg: 80 }, { date: '2024-03-07', weight_kg: 81 }], kg)
+ expect(p.bodyweight.map(b => b.w)).toEqual([81])
+ })
+})
+
+describe('mergeHevyRoutines adds and only replaces its own', () => {
+ it('never touches a routine it did not import, and reuses a custom that already exists by name and body part', () => {
+ const S = {
+ routines: [{ id: 'mine', name: 'Mine', ex: [{ id: '0025', sets: 3 }] }, { id: 'old', name: 'Old Hevy', hevyId: 'r1', ex: [] }],
+ customEx: [{ id: 'cu1', n: 'zorb', bp: 'waist' }],
+ }
+ const parsed = parseHevyRoutines([
+ { id: 'r1', title: 'Push', exercises: [{ exercise_template_id: 'ZZZ1', sets: [set()] }] },
+ { id: 'r2', title: 'Pull', exercises: [lat()] },
+ ], [T_LAT, { id: 'ZZZ1', title: 'Zorb', primary_muscle_group: 'abs' }], kg)
+ expect(mergeHevyRoutines(S, parsed)).toEqual({ added: 1, updated: 1 })
+ expect(S.routines.map(r => r.name)).toEqual(['Mine', 'Push', 'Pull'])
+ expect(S.routines[0]).toEqual({ id: 'mine', name: 'Mine', ex: [{ id: '0025', sets: 3 }] })
+ expect(S.routines[1].id).toBe('old') // replaced in place, id kept
+ expect(S.routines[1].ex[0].id).toBe('cu1') // "zorb" / waist already existed
+ expect(S.customEx).toHaveLength(1)
+ for (const r of S.routines.slice(1)) {
+ expect(Array.isArray(r.ex)).toBe(true)
+ expect(r.ex.length).toBeGreaterThan(0)
+ for (const e of r.ex) { expect(typeof e.id).toBe('string'); expect(e.sets).toBeGreaterThan(0) }
+ }
+ })
+})
diff --git a/frontend/src/lib/import-hevy.js b/frontend/src/lib/import-hevy.js
index bed02b3c8..899e981c1 100644
--- a/frontend/src/lib/import-hevy.js
+++ b/frontend/src/lib/import-hevy.js
@@ -101,8 +101,10 @@ export async function fetchHevyAccount(apiKey, { onProgress } = {}) {
/* ---------------------------------------------------------- template → id -- */
-// Hevy primary_muscle_group → openGym body-part for exercises we invent.
-const HEVY_BP = {
+// Hevy primary_muscle_group → openGym body-part for exercises we invent. Indexed straight from
+// the API's text, so it has no prototype: a plain object answers "constructor" and "__proto__"
+// with Object's own machinery, and that would ride into the store as a body part.
+const HEVY_BP = Object.assign(Object.create(null), {
biceps: 'upper arms', triceps: 'upper arms', forearms: 'lower arms',
chest: 'chest', lats: 'back', upper_back: 'back', lower_back: 'back',
traps: 'back', shoulders: 'shoulders',
@@ -110,7 +112,7 @@ const HEVY_BP = {
quadriceps: 'upper legs', hamstrings: 'upper legs', glutes: 'upper legs',
abductors: 'upper legs', adductors: 'upper legs', calves: 'lower legs',
cardio: 'cardio', full_body: 'upper legs', other: 'upper legs', neck: 'neck',
-}
+})
/**
* Resolve a Hevy exercise template to a catalogue id.
@@ -140,6 +142,9 @@ const p2 = n => String(n).padStart(2, '0')
/** Hevy ISO timestamps → local calendar date + ms-since-midnight (matches CSV import). */
export function localWhen(iso) {
+ // Hevy writes ISO strings. Anything else is not a time — null in particular, which Date
+ // reads as the epoch and would file the session under 1970.
+ if (typeof iso !== 'string') return null
const d = new Date(iso)
if (isNaN(d.getTime())) return null
const day = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`
@@ -156,7 +161,7 @@ function bpOfTemplate(t) {
function makeResolver(templates) {
const byId = new Map((templates || []).map(t => [t.id, t]))
const created = new Map()
- const unmatched = new Set()
+ const titleOf = new Map() // custom id → the name Hevy showed for it
const matchedIds = new Set()
const resolve = (templateId, fallbackTitle) => {
@@ -177,18 +182,23 @@ function makeResolver(templates) {
|| 'upper legs',
}
created.set(key, c)
- unmatched.add(t?.title || fallbackTitle || name)
+ titleOf.set(c.id, t?.title || fallbackTitle || name)
}
return c.id
}
+ // Everything is reported against the ids the parse actually kept: resolve() runs before an
+ // exercise's sets are read, so one whose sets all had nothing measured has been resolved and
+ // invented but points at nothing — and would otherwise be counted, listed under "added as your
+ // own", and (mergeHevyRoutines takes every custom it is given) put in the library on its own.
+ const kept = used => [...created.values()].filter(c => used.has(c.id))
return {
resolve,
byId,
- customEx: () => [...created.values()],
- unmatchedNames: () => [...unmatched].sort(),
- matchedCount: () => matchedIds.size,
- createdCount: () => created.size,
+ customEx: used => kept(used),
+ unmatchedNames: used => [...new Set(kept(used).map(c => titleOf.get(c.id)))].sort(),
+ matchedCount: used => [...matchedIds].filter(id => used.has(id)).length,
+ createdCount: used => kept(used).length,
}
}
@@ -212,12 +222,14 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
const start = localWhen(w.start_time)
const end = localWhen(w.end_time)
if (!start) { skipped++; continue }
+ // The history list renders the name as it is stored, so only text may become one.
+ const title = typeof w.title === 'string' ? w.title : ''
let day = byDate.get(start.d)
if (!day) {
- day = { ex: new Map(), name: w.title || '', start: start.t, end: end?.t ?? null }
+ day = { ex: new Map(), name: title, start: start.t, end: end?.t ?? null }
byDate.set(start.d, day)
- } else if (!day.name && w.title) day.name = w.title
+ } else if (!day.name && title) day.name = title
if (end?.t != null) day.end = end.t
for (const ex of w.exercises || []) {
@@ -225,8 +237,9 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
if (!id) { skipped++; continue }
if (EXIDX[id] && !String(id).startsWith('im')) matched++
- if (!day.ex.has(id)) day.ex.set(id, [])
- const list = day.ex.get(id)
+ // Filed only once a set lands in it: an exercise whose sets all had nothing measured would
+ // otherwise import as an entry with no sets, which nothing that reads a session back expects.
+ const list = day.ex.get(id) || []
for (const s of ex.sets || []) {
const warmup = /warm/i.test(String(s.type || ''))
@@ -234,7 +247,9 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
const reps = s.reps != null ? Math.round(s.reps) : 0
const wgt = toProfileWeight(s.weight_kg, unit)
const secs = s.duration_seconds != null ? Number(s.duration_seconds) : 0
- const km = s.distance_meters != null ? Number(s.distance_meters) / 1000 : 0
+ // A distance that is not a number would otherwise divide into a NaN speed.
+ const dist = Number(s.distance_meters)
+ const km = isFinite(dist) ? dist / 1000 : 0
if (!wgt && !reps && !secs && !km) { skipped++; continue }
const isCardio = (km > 0 || secs > 0) && !reps
@@ -250,10 +265,13 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
list.push(set)
sets++
}
+ if (list.length && !day.ex.has(id)) day.ex.set(id, list)
}
}
- const dates = [...byDate.keys()].sort()
+ // A day on which nothing measurable landed is not a workout — and imported, it would block the
+ // real one from a later export, since existing days win in mergeImport.
+ const dates = [...byDate.keys()].filter(d => byDate.get(d).ex.size).sort()
const outWorkouts = dates.map(d => {
const day = byDate.get(d)
const entries = [...day.ex.entries()].map(([id, ss]) => {
@@ -271,16 +289,17 @@ export function parseHevyWorkouts(workouts, templates, { unit = 'kg' } = {}) {
workout.vol = entries.reduce((a, e) => a + e.sets.reduce((b, s) => b + (isWarmupRow(s) ? 0 : (s.w || 0) * (s.r || 0)), 0), 0)
return workout
})
+ const used = new Set(outWorkouts.flatMap(w => w.entries.map(e => e.id)))
return {
kind: 'workouts',
source: 'Hevy',
workouts: outWorkouts,
- customEx: R.customEx(),
- matched: R.matchedCount(),
+ customEx: R.customEx(used),
+ matched: R.matchedCount(used),
matchedSets: matched,
- created: R.createdCount(),
- unmatchedNames: R.unmatchedNames(),
+ created: R.createdCount(used),
+ unmatchedNames: R.unmatchedNames(used),
sets, skipped, warmups,
fileUnit: 'kg',
mixedUnits: false,
@@ -358,14 +377,15 @@ export function parseHevyRoutines(routines, templates, { unit = 'kg' } = {}) {
})
}
+ const used = new Set(out.flatMap(r => r.ex.map(e => e.id)))
return {
kind: 'routines',
source: 'Hevy',
routines: out,
- customEx: R.customEx(),
- matched: R.matchedCount(),
- created: R.createdCount(),
- unmatchedNames: R.unmatchedNames(),
+ customEx: R.customEx(used),
+ matched: R.matchedCount(used),
+ created: R.createdCount(used),
+ unmatchedNames: R.unmatchedNames(used),
exerciseCount: out.reduce((n, r) => n + r.ex.length, 0),
converted: unit === 'lb',
}