UNPKG

@sports-alliance/sports-lib

Version:

A Library to for importing / exporting and processing GPX, TCX, FIT and JSON files from services such as Strava, Movescount, Garmin, Polar etc

283 lines (282 loc) 16.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const fs = __importStar(require("fs")); const path = __importStar(require("path")); const importer_suunto_json_1 = require("./importer.suunto.json"); const activity_parsing_options_1 = require("../../../../activities/activity-parsing-options"); const data_distance_1 = require("../../../../data/data.distance"); const data_ground_contact_time_1 = require("../../../../data/data.ground-contact-time"); const data_ground_contact_time_avg_1 = require("../../../../data/data.ground-contact-time-avg"); const data_ground_contact_time_max_1 = require("../../../../data/data.ground-contact-time-max"); const data_ground_contact_time_min_1 = require("../../../../data/data.ground-contact-time-min"); const data_vertical_oscillation_1 = require("../../../../data/data.vertical-oscillation"); const data_vertical_oscillation_avg_1 = require("../../../../data/data.vertical-oscillation-avg"); const data_vertical_oscillation_max_1 = require("../../../../data/data.vertical-oscillation-max"); const data_vertical_oscillation_min_1 = require("../../../../data/data.vertical-oscillation-min"); const data_fitness_age_1 = require("../../../../data/data.fitness-age"); const data_max_hr_setting_1 = require("../../../../data/data.max-hr-setting"); const data_heart_rate_1 = require("../../../../data/data.heart-rate"); const data_battery_charge_1 = require("../../../../data/data.battery-charge"); const data_battery_current_1 = require("../../../../data/data.battery-current"); const data_battery_voltage_1 = require("../../../../data/data.battery-voltage"); const data_stamina_1 = require("../../../../data/data.stamina"); const stream_regression_helper_1 = require("../integration/stream-regression.helper"); describe('EventImporterSuuntoJSON Integration', () => { // Go up 5 levels from src/events/adapters/importers/suunto -> sports-lib root const samplesDir = path.resolve(__dirname, '../../../../../samples/suunto'); // TODO(sports-lib): add explicit canonical-stream regression assertions for multi-device Suunto samples // so speed/distance-family output remains single-source and deterministic. function parseSuuntoFile(filePath, options) { return __awaiter(this, void 0, void 0, function* () { const fileString = fs.readFileSync(filePath, 'utf-8'); return importer_suunto_json_1.EventImporterSuuntoJSON.getFromJSONString(fileString, options); }); } const finiteNumbers = (values) => values.filter((value) => Number.isFinite(value)); it('should parse all sample suunto json files', () => __awaiter(void 0, void 0, void 0, function* () { if (!fs.existsSync(samplesDir)) { console.warn(`Samples directory not found at ${samplesDir}. Skipping integration tests.`); return; } const files = fs.readdirSync(samplesDir).filter(f => f.endsWith('.json')); if (files.length === 0) { console.warn('No .json files found in samples directory.'); return; } for (const file of files) { const filePath = path.join(samplesDir, file); try { const event = yield parseSuuntoFile(filePath); expect(event).toBeDefined(); expect(event.getActivities().length).toBeGreaterThan(0); event.getActivities().forEach(activity => { expect((0, stream_regression_helper_1.getDuplicateStreamTypes)(activity)).toEqual([]); expect((0, stream_regression_helper_1.getUniqueStreamTypes)(activity).length).toBeGreaterThan(0); }); } catch (error) { console.error(`❌ Failed to parse ${file}:`, error); throw error; } } })); it('should preserve stream-type regression coverage for curated suunto samples', () => __awaiter(void 0, void 0, void 0, function* () { const expectations = [ { fileName: 'running-with-extra-data.json', requiredTypes: [ data_distance_1.DataDistance.type, data_ground_contact_time_1.DataGroundContactTime.type, data_vertical_oscillation_1.DataVerticalOscillation.type, data_battery_charge_1.DataBatteryCharge.type, data_battery_current_1.DataBatteryCurrent.type, data_battery_voltage_1.DataBatteryVoltage.type ] }, { fileName: 'missing_hr.json', requiredTypes: [data_heart_rate_1.DataHeartRate.type, data_battery_charge_1.DataBatteryCharge.type, data_battery_current_1.DataBatteryCurrent.type, data_battery_voltage_1.DataBatteryVoltage.type] }, { fileName: '2026-03-06_08-14.json', requiredTypes: [ data_ground_contact_time_1.DataGroundContactTime.type, data_vertical_oscillation_1.DataVerticalOscillation.type, data_battery_charge_1.DataBatteryCharge.type, data_battery_current_1.DataBatteryCurrent.type, data_battery_voltage_1.DataBatteryVoltage.type ] } ]; for (const expectation of expectations) { const filePath = path.join(samplesDir, expectation.fileName); if (!fs.existsSync(filePath)) { console.warn(`Regression sample not found at ${filePath}. Skipping.`); continue; } const event = yield parseSuuntoFile(filePath); const activity = (0, stream_regression_helper_1.getPrimaryActivityForStreamRegression)(event); const streamTypes = new Set(activity.getAllStreams().map(stream => stream.type)); expectation.requiredTypes.forEach(streamType => { expect(streamTypes.has(streamType)).toBe(true); }); expect((0, stream_regression_helper_1.getDuplicateStreamTypes)(activity)).toEqual([]); } })); it('should keep stream output unchanged when includeTypes is set (current scope guard)', () => __awaiter(void 0, void 0, void 0, function* () { const filePath = path.join(samplesDir, 'running-with-extra-data.json'); if (!fs.existsSync(filePath)) { console.warn('running-with-extra-data.json not found. Skipping includeTypes scope guard test.'); return; } const baselineEvent = yield parseSuuntoFile(filePath, new activity_parsing_options_1.ActivityParsingOptions({ generateUnitStreams: false })); const includeFilteredEvent = yield parseSuuntoFile(filePath, new activity_parsing_options_1.ActivityParsingOptions({ generateUnitStreams: false, streams: { includeTypes: [data_distance_1.DataDistance.type] } })); const baselineActivity = baselineEvent .getActivities() .reduce((prev, current) => (prev.getDuration().getValue() > current.getDuration().getValue() ? prev : current)); const includeFilteredActivity = includeFilteredEvent .getActivities() .reduce((prev, current) => (prev.getDuration().getValue() > current.getDuration().getValue() ? prev : current)); const baselineStreamTypes = baselineActivity.getAllStreams().map(stream => stream.type); const includeFilteredStreamTypes = includeFilteredActivity.getAllStreams().map(stream => stream.type); expect(includeFilteredStreamTypes).toEqual(baselineStreamTypes); })); it('should map Suunto Endurance to Stamina without creating Potential Stamina', () => __awaiter(void 0, void 0, void 0, function* () { var _a, _b, _c; const filePath = path.join(samplesDir, 'ym780_Chengdu___3.27.4+2026-05-14_04.13.18-Running-2522C0000220.json'); const event = yield parseSuuntoFile(filePath, new activity_parsing_options_1.ActivityParsingOptions({ generateUnitStreams: false })); const activity = (0, stream_regression_helper_1.getPrimaryActivityForStreamRegression)(event); const staminaValues = finiteNumbers(activity.getStreamData(data_stamina_1.DataStamina.type)); const avgStamina = staminaValues.reduce((sum, value) => sum + value, 0) / staminaValues.length; expect(staminaValues).toHaveLength(3949); expect(staminaValues[0]).toBe(100); expect(staminaValues[staminaValues.length - 1]).toBe(71); expect((_a = activity.getStat(data_stamina_1.DataStaminaMin.type)) === null || _a === void 0 ? void 0 : _a.getValue()).toBe(Math.min(...staminaValues)); expect((_b = activity.getStat(data_stamina_1.DataStaminaMax.type)) === null || _b === void 0 ? void 0 : _b.getValue()).toBe(Math.max(...staminaValues)); expect((_c = activity.getStat(data_stamina_1.DataStaminaAvg.type)) === null || _c === void 0 ? void 0 : _c.getValue()).toBeCloseTo(avgStamina, 10); expect(activity.hasStreamData(data_stamina_1.DataPotentialStamina.type)).toBe(false); })); describe('running-with-extra-data.json', () => { let event; let activity; beforeAll(() => __awaiter(void 0, void 0, void 0, function* () { const filePath = path.join(samplesDir, 'running-with-extra-data.json'); if (!fs.existsSync(filePath)) { console.warn('running-with-extra-data.json not found. Skipping detailed tests.'); return; } event = yield parseSuuntoFile(filePath); // DEBUG: print one sample's date from the source file just blindly // (we can't easily access json here again without parsing, but we can infer from activity) // Find the main running activity (longest duration) activity = event .getActivities() .reduce((prev, current) => (prev.getDuration().getValue() > current.getDuration().getValue() ? prev : current)); })); it('should parse Ground Contact Time stream', () => { if (!activity) return; // Depending on the file structure, GCT might be in the first or second activity. // We selected the longest one. const hasStream = activity.hasStreamData(data_ground_contact_time_1.DataGroundContactTime.type); expect(hasStream).toBe(true); if (hasStream) { const stream = activity.getStreamData(data_ground_contact_time_1.DataGroundContactTime.type); expect(stream.length).toBeGreaterThan(0); } }); it('should parse Ground Contact Time stats (avg, max, min)', () => { if (!activity) return; const avgStat = activity.getStat(data_ground_contact_time_avg_1.DataGroundContactTimeAvg.type); const maxStat = activity.getStat(data_ground_contact_time_max_1.DataGroundContactTimeMax.type); const minStat = activity.getStat(data_ground_contact_time_min_1.DataGroundContactTimeMin.type); expect(avgStat).toBeDefined(); expect(avgStat === null || avgStat === void 0 ? void 0 : avgStat.getValue()).toBeCloseTo(255.969, 3); expect(maxStat).toBeDefined(); expect(maxStat === null || maxStat === void 0 ? void 0 : maxStat.getValue()).toBe(339); expect(minStat).toBeDefined(); expect(minStat === null || minStat === void 0 ? void 0 : minStat.getValue()).toBe(219); }); it('should parse Vertical Oscillation stream', () => { if (!activity) return; const hasStream = activity.hasStreamData(data_vertical_oscillation_1.DataVerticalOscillation.type); expect(hasStream).toBe(true); }); it('should parse Vertical Oscillation stats (avg, max, min)', () => { if (!activity) return; const avgStat = activity.getStat(data_vertical_oscillation_avg_1.DataVerticalOscillationAvg.type); const maxStat = activity.getStat(data_vertical_oscillation_max_1.DataVerticalOscillationMax.type); const minStat = activity.getStat(data_vertical_oscillation_min_1.DataVerticalOscillationMin.type); expect(avgStat).toBeDefined(); expect(avgStat === null || avgStat === void 0 ? void 0 : avgStat.getValue()).toBeCloseTo(74.359, 3); expect(maxStat).toBeDefined(); expect(maxStat === null || maxStat === void 0 ? void 0 : maxStat.getValue()).toBe(87); expect(minStat).toBeDefined(); expect(minStat === null || minStat === void 0 ? void 0 : minStat.getValue()).toBe(42); }); it('should parse Fitness Age from header (Event or Activity)', () => { let stat = event.getStat(data_fitness_age_1.DataFitnessAge.type); if (!stat && activity) { stat = activity.getStat(data_fitness_age_1.DataFitnessAge.type); } expect(stat).toBeDefined(); expect(stat === null || stat === void 0 ? void 0 : stat.getValue()).toBe(25); }); it('should parse Personal MaxHR from header (Event or Activity)', () => { let stat = event.getStat(data_max_hr_setting_1.DataMaxHRSetting.type); if (!stat && activity) { stat = activity.getStat(data_max_hr_setting_1.DataMaxHRSetting.type); } expect(stat).toBeDefined(); expect(stat === null || stat === void 0 ? void 0 : stat.getValue()).toBe(171); }); }); describe('missing_hr.json', () => { it('should keep direct HR stream when RR cannot produce enough valid HR samples', () => __awaiter(void 0, void 0, void 0, function* () { const filePath = path.join(samplesDir, 'missing_hr.json'); if (!fs.existsSync(filePath)) { console.warn('missing_hr.json not found. Skipping RR fallback test.'); return; } const event = yield parseSuuntoFile(filePath); const activity = event .getActivities() .reduce((prev, current) => (prev.getDuration().getValue() > current.getDuration().getValue() ? prev : current)); expect(activity.hasStreamData(data_heart_rate_1.DataHeartRate.type)).toBe(true); const hrValues = activity .getStreamData(data_heart_rate_1.DataHeartRate.type) .filter((value) => typeof value === 'number' && Number.isFinite(value)); expect(hrValues.length).toBeGreaterThan(1000); expect(Math.min(...hrValues)).toBeGreaterThan(40); expect(Math.max(...hrValues)).toBeLessThan(220); })); }); });