Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: support ZIP upload for Apple Health import, remove TSV import

Adam Eivy8ab189cfb0de
diff --git a/.changelog/v1.14.x.md b/.changelog/v1.14.x.md
index 6700b8f052..94178c3bad 100644
--- a/.changelog/v1.14.x.md
+++ b/.changelog/v1.14.x.md
@@ -4,8 +4,16 @@ Released: YYYY-MM-DD
## Overview
-Housekeeping release — remove sub-directory package-lock files from git tracking to reduce merge noise.
+Apple Health import improvements and meatspace cleanup.
+
+## Features
+
+- **ZIP upload for Apple Health import** — upload the Apple Health export ZIP directly instead of manually extracting `export.xml` first; server extracts and streams the XML automatically
## Improvements
- **Gitignore sub-directory lock files** — removed `client/`, `server/`, and `browser/` package-lock.json from git tracking and added them to `.gitignore`; only the root lock file is committed
+
+## Removed
+
+- **Meatspace TSV import** — removed unused TSV import endpoint, service, tests, validation schema, and UI
diff --git a/client/src/components/meatspace/tabs/ImportTab.jsx b/client/src/components/meatspace/tabs/ImportTab.jsx
index 6558cf98a5..872ccb080f 100644
--- a/client/src/components/meatspace/tabs/ImportTab.jsx
+++ b/client/src/components/meatspace/tabs/ImportTab.jsx
@@ -1,17 +1,10 @@
import { useState, useRef, useEffect } from 'react';
-import { Upload, FileSpreadsheet, FileJson, HeartPulse, CheckCircle, AlertCircle } from 'lucide-react';
+import { Upload, FileJson, HeartPulse, CheckCircle, AlertCircle } from 'lucide-react';
import * as api from '../../../services/api';
import socket from '../../../services/socket';
import BrailleSpinner from '../../BrailleSpinner';
export default function ImportTab({ onRefresh }) {
- // TSV import state
- const [importing, setImporting] = useState(false);
- const [result, setResult] = useState(null);
- const [error, setError] = useState(null);
- const [fileName, setFileName] = useState(null);
- const fileInputRef = useRef(null);
-
// JSON import state
const [jsonImporting, setJsonImporting] = useState(false);
const [jsonResult, setJsonResult] = useState(null);
@@ -42,36 +35,6 @@ export default function ImportTab({ onRefresh }) {
};
}, []);
- const handleFileSelect = async (e) => {
- const file = e.target.files?.[0];
- if (!file) return;
-
- setFileName(file.name);
- setError(null);
- setResult(null);
- setImporting(true);
-
- const reader = new FileReader();
- reader.onload = async (event) => {
- const content = event.target.result;
- const stats = await api.importMeatspaceTSV(content).catch(err => {
- setError(err.message);
- return null;
- });
-
- if (stats) {
- setResult(stats);
- onRefresh?.();
- }
- setImporting(false);
- };
- reader.onerror = () => {
- setError('Failed to read file');
- setImporting(false);
- };
- reader.readAsText(file);
- };
-
const handleJsonFileSelect = async (e) => {
const file = e.target.files?.[0];
if (!file) return;
@@ -119,8 +82,8 @@ export default function ImportTab({ onRefresh }) {
const file = e.target.files?.[0];
if (!file) return;
- if (!file.name.endsWith('.xml')) {
- setXmlError('Please select an .xml file. Extract the Apple Health ZIP and upload export.xml.');
+ if (!file.name.endsWith('.xml') && !file.name.endsWith('.zip')) {
+ setXmlError('Please select an .xml or .zip file from your Apple Health export.');
return;
}
@@ -139,95 +102,6 @@ export default function ImportTab({ onRefresh }) {
return (
<div className="space-y-6">
- {/* TSV Import */}
- <div className="bg-port-card border border-port-border rounded-xl p-6">
- <div className="flex items-center gap-2 mb-4">
- <FileSpreadsheet size={18} className="text-port-accent" />
- <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
- Health Spreadsheet Import (TSV)
- </h3>
- </div>
-
- <p className="text-sm text-gray-400 mb-4">
- Import your health tracking spreadsheet. Expects a TSV file with 3 header rows,
- 2 summary rows, then daily data. Covers alcohol, body composition,
- blood tests, epigenetic results, and eye prescriptions.
- </p>
- <p className="text-xs text-gray-500 mb-4">
- Import is idempotent — re-importing replaces all existing data.
- </p>
-
- <div className="flex items-center gap-4">
- <input
- ref={fileInputRef}
- type="file"
- accept=".tsv,.txt,.csv"
- onChange={handleFileSelect}
- className="hidden"
- />
- <button
- onClick={() => fileInputRef.current?.click()}
- disabled={importing}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent text-white rounded-lg hover:bg-port-accent/80 disabled:opacity-50 transition-colors"
- >
- {importing ? (
- <BrailleSpinner text="Importing" />
- ) : (
- <>
- <Upload size={16} />
- Choose TSV File
- </>
- )}
- </button>
- {fileName && !importing && (
- <span className="text-sm text-gray-400">{fileName}</span>
- )}
- </div>
-
- {/* Success */}
- {result && (
- <div className="mt-4 p-4 bg-port-success/10 border border-port-success/30 rounded-lg">
- <div className="flex items-center gap-2 mb-2">
- <CheckCircle size={16} className="text-port-success" />
- <span className="text-port-success font-medium">Import successful</span>
- </div>
- <div className="grid grid-cols-2 md:grid-cols-4 gap-3 text-sm">
- <div>
- <span className="text-gray-500">Daily entries</span>
- <p className="text-white font-semibold">{result.dailyEntries}</p>
- </div>
- <div>
- <span className="text-gray-500">Blood tests</span>
- <p className="text-white font-semibold">{result.bloodTests}</p>
- </div>
- <div>
- <span className="text-gray-500">Epigenetic tests</span>
- <p className="text-white font-semibold">{result.epigeneticTests}</p>
- </div>
- <div>
- <span className="text-gray-500">Eye exams</span>
- <p className="text-white font-semibold">{result.eyeExams}</p>
- </div>
- </div>
- {result.dateRange && (
- <p className="text-xs text-gray-400 mt-2">
- Date range: {result.dateRange.from} to {result.dateRange.to}
- </p>
- )}
- </div>
- )}
-
- {/* Error */}
- {error && (
- <div className="mt-4 p-4 bg-port-error/10 border border-port-error/30 rounded-lg">
- <div className="flex items-center gap-2">
- <AlertCircle size={16} className="text-port-error" />
- <span className="text-port-error">{error}</span>
- </div>
- </div>
- )}
- </div>
-
{/* Health Auto Export JSON Import */}
<div className="bg-port-card border border-port-border rounded-xl p-6">
<div className="flex items-center gap-2 mb-4">
@@ -320,11 +194,13 @@ export default function ImportTab({ onRefresh }) {
</div>
<p className="text-sm text-gray-400 mb-2">
- Import your Apple Health export. On your iPhone: Settings &gt; Health &gt; Export All Health Data.
- Extract the ZIP and select the export.xml file.
+ Import your Apple Health export. On your iPhone: open the <strong className="text-gray-300">Health</strong> app,
+ tap your <strong className="text-gray-300">profile icon</strong> (top right),
+ scroll down and tap <strong className="text-gray-300">Export All Health Data</strong>.
+ Upload the ZIP directly or extract it and select export.xml.
</p>
<p className="text-xs text-gray-500 mb-4">
- Extract the ZIP file first — upload the export.xml file directly.
+ You can upload the ZIP file as-is — the server will extract export.xml automatically.
Large exports (500MB+) are streamed without loading into memory.
</p>
@@ -332,7 +208,7 @@ export default function ImportTab({ onRefresh }) {
<input
ref={xmlFileInputRef}
type="file"
- accept=".xml"
+ accept=".xml,.zip"
onChange={handleXmlFileSelect}
className="hidden"
/>
@@ -346,7 +222,7 @@ export default function ImportTab({ onRefresh }) {
) : (
<>
<Upload size={16} />
- Choose XML File
+ Choose XML or ZIP File
</>
)}
</button>
diff --git a/client/src/services/api.js b/client/src/services/api.js
index d1710c7685..671516eb33 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1335,10 +1335,6 @@ export const updateAlcoholDrink = (date, index, data) => request(`/meatspace/alc
export const removeAlcoholDrink = (date, index) => request(`/meatspace/alcohol/log/${date}/${index}`, {
method: 'DELETE'
});
-export const importMeatspaceTSV = (content) => request('/meatspace/import/tsv', {
- method: 'POST',
- body: JSON.stringify({ content })
-});
export const getBloodTests = () => request('/meatspace/blood');
export const addBloodTest = (data) => request('/meatspace/blood', {
method: 'POST',
diff --git a/package-lock.json b/package-lock.json
index 90d78cd98d..cb37a07e13 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "portos",
- "version": "1.14.5",
+ "version": "1.15.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "portos",
- "version": "1.14.5",
+ "version": "1.15.0",
"license": "MIT",
"dependencies": {
"express": "^4.21.2",
diff --git a/package.json b/package.json
index 3c70e2d312..de246d10a6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "portos",
- "version": "1.14.5",
+ "version": "1.15.0",
"private": true,
"description": "Local dev machine App OS portal",
"author": "Adam Eivy (@antic|@atomantic)",
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index 0ec4b59a80..40bc609086 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -112,9 +112,3 @@ export const eyeExamUpdateSchema = z.object({
});
// =============================================================================
-// TSV IMPORT
-// =============================================================================
-
-export const tsvImportSchema = z.object({
- content: z.string().min(1).max(10 * 1024 * 1024)
-});
diff --git a/server/package.json b/server/package.json
index 4e30d7249b..ca5e721b8b 100644
--- a/server/package.json
+++ b/server/package.json
@@ -21,6 +21,7 @@
"sax": "^1.4.4",
"socket.io": "^4.8.3",
"socket.io-client": "^4.8.3",
+ "unzipper": "^0.12.3",
"uuid": "^11.0.3",
"ws": "^8.18.0",
"zod": "^3.24.1"
diff --git a/server/routes/appleHealth.js b/server/routes/appleHealth.js
index 30cb07ecba..3d574c20f0 100644
--- a/server/routes/appleHealth.js
+++ b/server/routes/appleHealth.js
@@ -1,6 +1,9 @@
import { Router } from 'express';
import { tmpdir } from 'os';
+import { join } from 'path';
+import { createReadStream, createWriteStream, promises as fs } from 'fs';
import multer from 'multer';
+import { Parse as unzipParse } from 'unzipper';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { healthIngestSchema } from '../lib/appleHealthValidation.js';
@@ -13,17 +16,30 @@ import {
getCorrelationData
} from '../services/appleHealthQuery.js';
+const isZip = (file) =>
+ file.mimetype === 'application/zip' ||
+ file.mimetype === 'application/x-zip-compressed' ||
+ file.originalname.endsWith('.zip');
+
+const isXml = (file) =>
+ file.mimetype === 'text/xml' ||
+ file.mimetype === 'application/xml' ||
+ file.originalname.endsWith('.xml');
+
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, tmpdir()),
- filename: (req, file, cb) => cb(null, `apple-health-${Date.now()}.xml`)
+ filename: (req, file, cb) => {
+ const ext = isZip(file) ? '.zip' : '.xml';
+ cb(null, `apple-health-${Date.now()}${ext}`);
+ }
}),
limits: { fileSize: 2 * 1024 * 1024 * 1024 }, // 2GB max
fileFilter: (req, file, cb) => {
- if (file.mimetype === 'text/xml' || file.mimetype === 'application/xml' || file.originalname.endsWith('.xml')) {
+ if (isXml(file) || isZip(file)) {
cb(null, true);
} else {
- cb(new ServerError('Only XML files are accepted', { status: 400, code: 'BAD_REQUEST' }));
+ cb(new ServerError('Only XML or ZIP files are accepted', { status: 400, code: 'BAD_REQUEST' }));
}
}
});
@@ -72,11 +88,40 @@ router.get('/correlation', asyncHandler(async (req, res) => {
}));
// POST /api/health/import/xml
-// Accepts Apple Health export.xml via multipart upload (multer diskStorage — no OOM on 500MB+)
+// Accepts Apple Health export.xml or ZIP via multipart upload (multer diskStorage — no OOM on 500MB+)
router.post('/import/xml', upload.single('file'), asyncHandler(async (req, res) => {
const io = req.app.get('io');
- const filePath = req.file?.path;
+ let filePath = req.file?.path;
if (!filePath) throw new ServerError('No file uploaded', { status: 400, code: 'BAD_REQUEST' });
+
+ // If ZIP, extract export.xml to a temp file
+ if (req.file.originalname.endsWith('.zip') || isZip(req.file)) {
+ const xmlPath = join(tmpdir(), `apple-health-${Date.now()}.xml`);
+ let found = false;
+
+ await new Promise((resolve, reject) => {
+ let settled = false;
+ const settle = (fn) => (...args) => { if (!settled) { settled = true; fn(...args); } };
+ createReadStream(filePath)
+ .pipe(unzipParse())
+ .on('entry', (entry) => {
+ if (entry.path === 'apple_health_export/export.xml' || entry.path === 'export.xml') {
+ found = true;
+ entry.pipe(createWriteStream(xmlPath))
+ .on('finish', settle(resolve))
+ .on('error', settle(reject));
+ } else {
+ entry.autodrain();
+ }
+ })
+ .on('close', () => { if (!found) settle(reject)(new ServerError('ZIP does not contain export.xml', { status: 400, code: 'BAD_REQUEST' })); })
+ .on('error', settle(reject));
+ });
+
+ await fs.unlink(filePath);
+ filePath = xmlPath;
+ }
+
const result = await importAppleHealthXml(filePath, io);
res.json(result);
}));
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 5916be0be0..ebb795244d 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -11,12 +11,10 @@ import {
epigeneticTestSchema,
eyeExamSchema,
eyeExamUpdateSchema,
- tsvImportSchema
} from '../lib/meatspaceValidation.js';
import * as meatspaceService from '../services/meatspace.js';
import * as alcoholService from '../services/meatspaceAlcohol.js';
import * as healthService from '../services/meatspaceHealth.js';
-import { importTSV } from '../services/meatspaceImport.js';
const router = Router();
@@ -254,21 +252,5 @@ router.delete('/eyes/:index', asyncHandler(async (req, res) => {
res.json(removed);
}));
-// =============================================================================
-// IMPORT
-// =============================================================================
-
-/**
- * POST /api/meatspace/import/tsv
- * Import TSV spreadsheet (5MB limit handled by express.json middleware)
- */
-router.post('/import/tsv', asyncHandler(async (req, res) => {
- const { content } = validateRequest(tsvImportSchema, req.body);
- const stats = await importTSV(content);
- if (stats.error) {
- throw new ServerError(stats.error, { status: 400, code: 'IMPORT_FAILED' });
- }
- res.json(stats);
-}));
export default router;
diff --git a/server/services/meatspaceImport.js b/server/services/meatspaceImport.js
deleted file mode 100644
index 74e7ee2026..0000000000
--- a/server/services/meatspaceImport.js
+++ /dev/null
@@ -1,349 +0,0 @@
-/**
- * MeatSpace TSV Import Service
- *
- * Parses the user's health spreadsheet (3 header rows + 2 summary rows + data).
- * Hardcoded column mapping for the specific 257-column layout.
- */
-
-import { writeFile } from 'fs/promises';
-import { join } from 'path';
-import { PATHS, ensureDir } from '../lib/fileUtils.js';
-
-const MEATSPACE_DIR = PATHS.meatspace;
-const DAILY_LOG_FILE = join(MEATSPACE_DIR, 'daily-log.json');
-const BLOOD_TESTS_FILE = join(MEATSPACE_DIR, 'blood-tests.json');
-const EPIGENETIC_TESTS_FILE = join(MEATSPACE_DIR, 'epigenetic-tests.json');
-const EYES_FILE = join(MEATSPACE_DIR, 'eyes.json');
-
-// Column indices (0-based), verified against actual TSV headers
-const COL = {
- DATE: 2,
- // Nutrition (3-11)
- CALORIES: 3,
- FAT: 4,
- SAT_FAT: 5,
- TRANS_FAT: 6,
- POLY_FAT: 7,
- MONO_FAT: 8,
- CARBS: 9,
- FIBER: 10,
- SUGAR: 11,
- // Alcohol summary
- ALCOHOL_GRAMS: 12,
- // Body composition (16-21)
- WEIGHT_LBS: 16,
- WEIGHT_KG: 17,
- MUSCLE_PCT: 18,
- FAT_PCT: 19,
- BONE_MASS: 20,
- TEMPERATURE: 21,
- // Protein columns (96-112)
- PROTEIN_START: 96,
- PROTEIN_END: 112,
- // Individual beverages (119-178) — names in row 0, ABV in row 1, serving oz in row 2
- BEVERAGE_START: 119,
- BEVERAGE_END: 178,
- // Elysium Index (179-190)
- EPIGENETIC_START: 179,
- EPIGENETIC_END: 190,
- // Blood tests (193-245)
- BLOOD_START: 193,
- BLOOD_END: 245,
- // Eye prescription (246-251)
- EYE_START: 246,
- EYE_END: 251
-};
-
-// Epigenetic field names (indices relative to EPIGENETIC_START)
-const EPIGENETIC_FIELDS = [
- 'chronologicalAge', 'biologicalAge', 'paceOfAging',
- 'brain', 'liver', 'metabolic', 'immune', 'hormone',
- 'kidney', 'heart', 'inflammation', 'blood'
-];
-
-// Eye field names (indices relative to EYE_START)
-// TSV order: Left OD Sphere, Left Cylinder, Left Axis, Right OS Sphere, Right Cylinder, Right Axis
-const EYE_FIELDS = [
- 'leftSphere', 'leftCylinder', 'leftAxis',
- 'rightSphere', 'rightCylinder', 'rightAxis'
-];
-
-// === Parsing Helpers ===
-
-function parseNum(val) {
- if (val === undefined || val === null || val === '' || val === '-') return null;
- const cleaned = String(val).replace(/,/g, '').trim();
- if (!cleaned) return null;
- const n = Number(cleaned);
- return isNaN(n) ? null : n;
-}
-
-function parseDate(val) {
- if (!val) return null;
- // Convert YYYY/MM/DD to YYYY-MM-DD
- const cleaned = String(val).trim().replace(/\//g, '-');
- if (!/^\d{4}-\d{2}-\d{2}$/.test(cleaned)) return null;
- return cleaned;
-}
-
-function isEmptyRow(cells) {
- return cells.every(c => !c || c.trim() === '' || c.trim() === '-');
-}
-
-// === Beverage Parsing ===
-
-function parseBeverages(row, beverageNames, beverageABVs, beverageSizes) {
- const drinks = [];
- let totalStandardDrinks = 0;
-
- for (let i = COL.BEVERAGE_START; i <= COL.BEVERAGE_END; i++) {
- const count = parseNum(row[i]);
- if (!count || count <= 0) continue;
-
- const idx = i - COL.BEVERAGE_START;
- const rawAbv = parseNum(beverageABVs[idx]) || 5;
- const name = beverageNames[idx] || `${rawAbv}% ABV`;
- const abv = rawAbv;
- const servingOz = parseNum(beverageSizes[idx]) || 12;
-
- const oz = servingOz * count;
- const pureAlcoholOz = oz * (abv / 100);
- const standardDrinks = pureAlcoholOz / 0.6;
-
- drinks.push({ name, abv, oz, count: 1 });
- totalStandardDrinks += standardDrinks;
- }
-
- return { drinks, standardDrinks: Math.round(totalStandardDrinks * 100) / 100 };
-}
-
-// === Blood Test Parsing ===
-
-function parseBloodTests(row, bloodHeaders) {
- const result = {};
- let hasAny = false;
-
- for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {
- const val = parseNum(row[i]);
- if (val === null) continue;
- const idx = i - COL.BLOOD_START;
- const header = (bloodHeaders[idx] || `blood_${idx}`).toLowerCase().replace(/[^a-z0-9]/g, '_');
- result[header] = val;
- hasAny = true;
- }
-
- return hasAny ? result : null;
-}
-
-// === Epigenetic Parsing ===
-
-function parseEpigenetic(row) {
- const result = {};
-
- for (let i = 0; i < EPIGENETIC_FIELDS.length; i++) {
- const val = parseNum(row[COL.EPIGENETIC_START + i]);
- if (val === null) continue;
- result[EPIGENETIC_FIELDS[i]] = val;
- }
-
- // Only count as a real epigenetic test if biologicalAge or paceOfAging is present
- // (chronologicalAge alone is just the user's age, populated on every row)
- if (result.biologicalAge == null && result.paceOfAging == null) return null;
-
- // Separate organ scores from top-level fields
- const organScores = {};
- const topLevel = {};
- const organFields = ['brain', 'liver', 'metabolic', 'immune', 'hormone', 'kidney', 'heart', 'inflammation', 'blood'];
- for (const [key, val] of Object.entries(result)) {
- if (organFields.includes(key)) {
- organScores[key] = val;
- } else {
- topLevel[key] = val;
- }
- }
-
- return { ...topLevel, organScores };
-}
-
-// === Eye Rx Parsing ===
-
-function parseEyes(row) {
- const result = {};
- let hasAny = false;
-
- for (let i = 0; i < EYE_FIELDS.length; i++) {
- const val = parseNum(row[COL.EYE_START + i]);
- if (val === null) continue;
- result[EYE_FIELDS[i]] = val;
- hasAny = true;
- }
-
- return hasAny ? result : null;
-}
-
-// === Main Import Function ===
-
-export async function importTSV(content) {
- await ensureDir(MEATSPACE_DIR);
-
- const lines = content.split('\n');
- if (lines.length < 6) {
- return { error: 'TSV file too short. Expected at least 6 rows (3 headers + 2 summaries + data).' };
- }
-
- // Parse header rows
- const headerRow1 = lines[0].split('\t'); // Category headers
- const headerRow2 = lines[1].split('\t'); // Item names (beverage names, blood test names)
- const headerRow3 = lines[2].split('\t'); // Serving sizes, reference ranges, units
-
- // Extract beverage metadata from headers
- // Row 0 has beverage names, Row 1 has ABV values (e.g. "5.4%"), Row 2 has serving sizes in oz
- const beverageNames = [];
- const beverageABVs = [];
- const beverageSizes = [];
- for (let i = COL.BEVERAGE_START; i <= COL.BEVERAGE_END; i++) {
- const idx = i - COL.BEVERAGE_START;
- beverageNames[idx] = headerRow1[i] || '';
- // ABV is in row 1 as "X.X%" format
- const abvMatch = String(headerRow2[i] || '').match(/(\d+\.?\d*)%/);
- beverageABVs[idx] = abvMatch ? abvMatch[1] : '5';
- beverageSizes[idx] = headerRow3[i] || '12';
- }
-
- // Extract blood test names from row 2
- const bloodHeaders = [];
- for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {
- bloodHeaders[i - COL.BLOOD_START] = headerRow2[i] || '';
- }
-
- // Extract blood reference ranges from row 3
- const referenceRanges = {};
- for (let i = COL.BLOOD_START; i <= COL.BLOOD_END; i++) {
- const idx = i - COL.BLOOD_START;
- const header = (bloodHeaders[idx] || '').toLowerCase().replace(/[^a-z0-9]/g, '_');
- const rangeStr = String(headerRow3[i] || '');
- const rangeMatch = rangeStr.match(/([\d.]+)\s*-\s*([\d.]+)/);
- if (rangeMatch && header) {
- referenceRanges[header] = {
- min: parseFloat(rangeMatch[1]),
- max: parseFloat(rangeMatch[2]),
- label: bloodHeaders[idx] || header
- };
- }
- }
-
- // Data starts at row 5 (0-indexed: rows 0-2 are headers, rows 3-4 are summaries)
- const dailyEntries = [];
- const bloodTests = [];
- const epigeneticTests = [];
- const eyeExams = [];
-
- for (let lineIdx = 5; lineIdx < lines.length; lineIdx++) {
- const line = lines[lineIdx];
- if (!line.trim()) continue;
-
- const cells = line.split('\t');
- if (isEmptyRow(cells)) continue;
-
- const date = parseDate(cells[COL.DATE]);
- if (!date) continue;
-
- // Nutrition
- const nutrition = {};
- const cal = parseNum(cells[COL.CALORIES]);
- if (cal !== null) nutrition.calories = cal;
- const fat = parseNum(cells[COL.FAT]);
- if (fat !== null) nutrition.fatG = fat;
- const satFat = parseNum(cells[COL.SAT_FAT]);
- if (satFat !== null) nutrition.satFatG = satFat;
- const transFat = parseNum(cells[COL.TRANS_FAT]);
- if (transFat !== null) nutrition.transFatG = transFat;
- const polyFat = parseNum(cells[COL.POLY_FAT]);
- if (polyFat !== null) nutrition.polyFatG = polyFat;
- const monoFat = parseNum(cells[COL.MONO_FAT]);
- if (monoFat !== null) nutrition.monoFatG = monoFat;
- const carbs = parseNum(cells[COL.CARBS]);
- if (carbs !== null) nutrition.carbG = carbs;
- const fiber = parseNum(cells[COL.FIBER]);
- if (fiber !== null) nutrition.fiberG = fiber;
- const sugar = parseNum(cells[COL.SUGAR]);
- if (sugar !== null) nutrition.sugarG = sugar;
-
- // Body composition
- const body = {};
- const weightLbs = parseNum(cells[COL.WEIGHT_LBS]);
- if (weightLbs !== null) body.weightLbs = weightLbs;
- const weightKg = parseNum(cells[COL.WEIGHT_KG]);
- if (weightKg !== null) body.weightKg = weightKg;
- const musclePct = parseNum(cells[COL.MUSCLE_PCT]);
- if (musclePct !== null) body.musclePct = musclePct;
- const fatPct = parseNum(cells[COL.FAT_PCT]);
- if (fatPct !== null) body.fatPct = fatPct;
- const boneMass = parseNum(cells[COL.BONE_MASS]);
- if (boneMass !== null) body.boneMass = boneMass;
- const temp = parseNum(cells[COL.TEMPERATURE]);
- if (temp !== null) body.temperature = temp;
-
- // Alcohol
- const alcohol = parseBeverages(cells, beverageNames, beverageABVs, beverageSizes);
-
- // Build daily entry (only include populated sections)
- const entry = { date };
- if (Object.keys(nutrition).length > 0) entry.nutrition = nutrition;
- if (alcohol.drinks.length > 0) entry.alcohol = alcohol;
- if (Object.keys(body).length > 0) entry.body = body;
-
- // Only add if entry has data beyond just the date
- if (Object.keys(entry).length > 1) {
- dailyEntries.push(entry);
- }
-
- // Blood tests (sparse - check if any blood values exist)
- const bloodData = parseBloodTests(cells, bloodHeaders);
- if (bloodData) {
- bloodTests.push({ date, ...bloodData });
- }
-
- // Epigenetic (sparse)
- const epiData = parseEpigenetic(cells);
- if (epiData) {
- epigeneticTests.push({ date, ...epiData });
- }
-
- // Eyes (sparse)
- const eyeData = parseEyes(cells);
- if (eyeData) {
- eyeExams.push({ date, ...eyeData });
- }
- }
-
- // Sort entries by date
- dailyEntries.sort((a, b) => a.date.localeCompare(b.date));
- bloodTests.sort((a, b) => a.date.localeCompare(b.date));
- epigeneticTests.sort((a, b) => a.date.localeCompare(b.date));
- eyeExams.sort((a, b) => a.date.localeCompare(b.date));
-
- // Write all data files
- const lastEntryDate = dailyEntries.length > 0 ? dailyEntries[dailyEntries.length - 1].date : null;
-
- await Promise.all([
- writeFile(DAILY_LOG_FILE, JSON.stringify({ entries: dailyEntries, lastEntryDate }, null, 2)),
- writeFile(BLOOD_TESTS_FILE, JSON.stringify({ tests: bloodTests, referenceRanges }, null, 2)),
- writeFile(EPIGENETIC_TESTS_FILE, JSON.stringify({ tests: epigeneticTests }, null, 2)),
- writeFile(EYES_FILE, JSON.stringify({ exams: eyeExams }, null, 2))
- ]);
-
- const stats = {
- dailyEntries: dailyEntries.length,
- bloodTests: bloodTests.length,
- epigeneticTests: epigeneticTests.length,
- eyeExams: eyeExams.length,
- dateRange: dailyEntries.length > 0
- ? { from: dailyEntries[0].date, to: lastEntryDate }
- : null
- };
-
- console.log(`📊 MeatSpace import: ${stats.dailyEntries} daily entries, ${stats.bloodTests} blood tests, ${stats.epigeneticTests} epigenetic, ${stats.eyeExams} eye exams`);
-
- return stats;
-}
diff --git a/server/services/meatspaceImport.test.js b/server/services/meatspaceImport.test.js
deleted file mode 100644
index d4ed2ccf6e..0000000000
--- a/server/services/meatspaceImport.test.js
+++ /dev/null
@@ -1,205 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-// Mock fs and fileUtils to avoid actual file I/O
-vi.mock('fs/promises', () => ({
- writeFile: vi.fn().mockResolvedValue(undefined),
- readFile: vi.fn().mockResolvedValue('{}')
-}));
-
-vi.mock('../lib/fileUtils.js', () => ({
- PATHS: { meatspace: '/tmp/test-meatspace' },
- ensureDir: vi.fn().mockResolvedValue(undefined)
-}));
-
-import { writeFile } from 'fs/promises';
-import { importTSV } from './meatspaceImport.js';
-
-// =============================================================================
-// HELPER: Build TSV content
-// =============================================================================
-
-function buildTSV({ headerRow1, headerRow2, headerRow3, summaryRow1, summaryRow2, dataRows }) {
- return [headerRow1, headerRow2, headerRow3, summaryRow1, summaryRow2, ...dataRows].join('\n');
-}
-
-function makeEmptyHeaders(count) {
- return new Array(count).fill('').join('\t');
-}
-
-// Build a minimal TSV with just date and nutrition columns
-function buildMinimalTSV(dataRows) {
- // Columns: 0=empty, 1=empty, 2=date, 3=cal, 4=fat, 5=satFat, 6=transFat, 7=polyFat, 8=monoFat, 9=carb, 10=fiber, 11=sugar
- const colCount = 250;
- const row1 = makeEmptyHeaders(colCount);
- const row2 = makeEmptyHeaders(colCount);
- const row3 = makeEmptyHeaders(colCount);
- const sum1 = makeEmptyHeaders(colCount);
- const sum2 = makeEmptyHeaders(colCount);
-
- const rows = dataRows.map(row => {
- const cells = new Array(colCount).fill('');
- if (row.date) cells[2] = row.date;
- if (row.calories != null) cells[3] = String(row.calories);
- if (row.fat != null) cells[4] = String(row.fat);
- if (row.carbs != null) cells[9] = String(row.carbs);
- if (row.fiber != null) cells[10] = String(row.fiber);
- if (row.sugar != null) cells[11] = String(row.sugar);
- // Body (cols 16-21)
- if (row.weightLbs != null) cells[16] = String(row.weightLbs);
- if (row.weightKg != null) cells[17] = String(row.weightKg);
- return cells.join('\t');
- });
-
- return buildTSV({
- headerRow1: row1,
- headerRow2: row2,
- headerRow3: row3,
- summaryRow1: sum1,
- summaryRow2: sum2,
- dataRows: rows
- });
-}
-
-// =============================================================================
-// TESTS
-// =============================================================================
-
-describe('importTSV', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('rejects files with fewer than 6 lines', async () => {
- const result = await importTSV('line1\nline2\nline3');
- expect(result.error).toMatch(/too short/i);
- });
-
- it('parses daily entries with nutrition data', async () => {
- const tsv = buildMinimalTSV([
- { date: '2024/01/15', calories: 1500, fat: 65, carbs: 180, fiber: 25, sugar: 40 },
- { date: '2024/01/16', calories: 1800, fat: 70, carbs: 200 }
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(2);
- expect(result.dateRange.from).toBe('2024-01-15');
- expect(result.dateRange.to).toBe('2024-01-16');
-
- // Check that writeFile was called with parsed data
- const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));
- expect(dailyLogCall).toBeTruthy();
-
- const dailyLog = JSON.parse(dailyLogCall[1]);
- expect(dailyLog.entries).toHaveLength(2);
- expect(dailyLog.entries[0].date).toBe('2024-01-15');
- expect(dailyLog.entries[0].nutrition.calories).toBe(1500);
- expect(dailyLog.entries[0].nutrition.fatG).toBe(65);
- expect(dailyLog.entries[0].nutrition.carbG).toBe(180);
- expect(dailyLog.entries[0].nutrition.fiberG).toBe(25);
- expect(dailyLog.entries[0].nutrition.sugarG).toBe(40);
- });
-
- it('converts YYYY/MM/DD date format to YYYY-MM-DD', async () => {
- const tsv = buildMinimalTSV([
- { date: '2023/02/04', calories: 1000 }
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(1);
-
- const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));
- const dailyLog = JSON.parse(dailyLogCall[1]);
- expect(dailyLog.entries[0].date).toBe('2023-02-04');
- });
-
- it('parses body composition data', async () => {
- const tsv = buildMinimalTSV([
- { date: '2024/03/10', weightLbs: 158, weightKg: 71.67 }
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(1);
-
- const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));
- const dailyLog = JSON.parse(dailyLogCall[1]);
- expect(dailyLog.entries[0].body.weightLbs).toBe(158);
- expect(dailyLog.entries[0].body.weightKg).toBe(71.67);
- });
-
- it('skips rows without valid dates', async () => {
- const tsv = buildMinimalTSV([
- { date: '', calories: 500 },
- { date: 'invalid', calories: 600 },
- { date: '2024/01/01', calories: 700 }
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(1);
- });
-
- it('skips empty data rows', async () => {
- const tsv = buildMinimalTSV([
- { date: '2024/01/01', calories: 700 },
- { date: '2024/01/02' } // No data besides date
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(1);
- });
-
- it('sorts entries by date', async () => {
- const tsv = buildMinimalTSV([
- { date: '2024/03/15', calories: 1500 },
- { date: '2024/01/10', calories: 1200 },
- { date: '2024/02/20', calories: 1800 }
- ]);
-
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(3);
-
- const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));
- const dailyLog = JSON.parse(dailyLogCall[1]);
- expect(dailyLog.entries[0].date).toBe('2024-01-10');
- expect(dailyLog.entries[1].date).toBe('2024-02-20');
- expect(dailyLog.entries[2].date).toBe('2024-03-15');
- });
-
- it('handles dash and empty values as null', async () => {
- const colCount = 250;
- const row1 = makeEmptyHeaders(colCount);
- const row2 = makeEmptyHeaders(colCount);
- const row3 = makeEmptyHeaders(colCount);
- const sum1 = makeEmptyHeaders(colCount);
- const sum2 = makeEmptyHeaders(colCount);
-
- const cells = new Array(colCount).fill('');
- cells[2] = '2024/01/01';
- cells[3] = '1000'; // calories
- cells[4] = '-'; // fat = dash
- cells[9] = ''; // carbs = empty
-
- const tsv = [row1, row2, row3, sum1, sum2, cells.join('\t')].join('\n');
- const result = await importTSV(tsv);
- expect(result.dailyEntries).toBe(1);
-
- const dailyLogCall = writeFile.mock.calls.find(c => c[0].includes('daily-log.json'));
- const dailyLog = JSON.parse(dailyLogCall[1]);
- expect(dailyLog.entries[0].nutrition.calories).toBe(1000);
- expect(dailyLog.entries[0].nutrition.fatG).toBeUndefined();
- expect(dailyLog.entries[0].nutrition.carbG).toBeUndefined();
- });
-
- it('writes all four output files', async () => {
- const tsv = buildMinimalTSV([
- { date: '2024/01/01', calories: 1000 }
- ]);
-
- await importTSV(tsv);
-
- const fileNames = writeFile.mock.calls.map(c => c[0]);
- expect(fileNames.some(f => f.includes('daily-log.json'))).toBe(true);
- expect(fileNames.some(f => f.includes('blood-tests.json'))).toBe(true);
- expect(fileNames.some(f => f.includes('epigenetic-tests.json'))).toBe(true);
- expect(fileNames.some(f => f.includes('eyes.json'))).toBe(true);
- });
-});