Initial commit of counter

This commit is contained in:
2026-11-14 17:16:57 +00:00
commit a397c2d3a7
27 changed files with 5196 additions and 0 deletions
+165
View File
@@ -0,0 +1,165 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { DatabaseSync } = require('node:sqlite');
const DATA_DIR = process.env.DATA_DIR || path.join(__dirname, '..', 'data');
fs.mkdirSync(DATA_DIR, { recursive: true });
const db = new DatabaseSync(path.join(DATA_DIR, 'counter.db'));
db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS profile (
id INTEGER PRIMARY KEY CHECK (id = 1),
name TEXT NOT NULL DEFAULT '',
sex TEXT NOT NULL DEFAULT 'male',
age INTEGER NOT NULL DEFAULT 30,
height_cm REAL NOT NULL DEFAULT 175,
weight_kg REAL NOT NULL DEFAULT 75,
goal TEXT NOT NULL DEFAULT 'maintain',
rate_lb_week REAL NOT NULL DEFAULT 0.5,
diet TEXT NOT NULL DEFAULT 'any',
protein_target_g REAL,
onboarded INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
meal TEXT NOT NULL DEFAULT 'snack',
name TEXT NOT NULL,
brand TEXT,
barcode TEXT,
grams REAL,
kcal REAL NOT NULL DEFAULT 0,
protein_g REAL NOT NULL DEFAULT 0,
carbs_g REAL NOT NULL DEFAULT 0,
fat_g REAL NOT NULL DEFAULT 0,
fiber_g REAL NOT NULL DEFAULT 0,
sugar_g REAL NOT NULL DEFAULT 0,
sodium_mg REAL NOT NULL DEFAULT 0,
image_url TEXT,
source TEXT NOT NULL DEFAULT 'manual',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS activities (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
type TEXT NOT NULL,
name TEXT NOT NULL,
steps INTEGER,
minutes REAL,
met REAL,
kcal REAL NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'manual',
external_id TEXT,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS food_cache (
barcode TEXT PRIMARY KEY,
payload TEXT NOT NULL,
fetched_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS plan_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
meal TEXT NOT NULL,
recipe_id TEXT NOT NULL,
name TEXT NOT NULL,
kcal REAL NOT NULL DEFAULT 0,
protein_g REAL NOT NULL DEFAULT 0,
carbs_g REAL NOT NULL DEFAULT 0,
fat_g REAL NOT NULL DEFAULT 0,
servings REAL NOT NULL DEFAULT 1,
style TEXT NOT NULL DEFAULT 'any',
sort INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_entries_date ON entries (date);
CREATE INDEX IF NOT EXISTS idx_activities_date ON activities (date);
CREATE INDEX IF NOT EXISTS idx_plan_date ON plan_items (date);
`);
db.exec(`
INSERT OR IGNORE INTO settings (key, value) VALUES ('pound_week_max', '7');
INSERT OR IGNORE INTO settings (key, value) VALUES ('default_units', 'imperial');
`);
// Migrate databases created before activity imports existed.
const activityColumns = db
.prepare("SELECT name FROM pragma_table_info('activities')")
.all()
.map((column) => column.name);
if (!activityColumns.includes('source')) {
db.exec("ALTER TABLE activities ADD COLUMN source TEXT NOT NULL DEFAULT 'manual'");
}
if (!activityColumns.includes('external_id')) {
db.exec('ALTER TABLE activities ADD COLUMN external_id TEXT');
}
db.exec(
'CREATE UNIQUE INDEX IF NOT EXISTS idx_activities_external ON activities (external_id) WHERE external_id IS NOT NULL'
);
db.prepare(
`INSERT OR IGNORE INTO profile
(id, name, sex, age, height_cm, weight_kg, goal, rate_lb_week, diet, protein_target_g, onboarded, updated_at)
VALUES (1, '', 'male', 30, 175, 75, 'maintain', 0.5, 'any', NULL, 0, ?)`
).run(new Date().toISOString());
function getProfile() {
const row = db.prepare('SELECT * FROM profile WHERE id = 1').get();
const settings = getSettings();
return { ...row, poundWeekMax: Number(settings.pound_week_max) || 7, units: settings.default_units || 'imperial' };
}
function getSettings() {
const rows = db.prepare('SELECT key, value FROM settings ORDER BY key').all();
const s = {};
for (const r of rows) s[r.key] = r.value;
return s;
}
function updateProfile(patch) {
const p = { ...getProfile(), ...patch };
db.exec(`
INSERT OR IGNORE INTO settings (key, value) VALUES ('pound_week_max', '7');
INSERT OR IGNORE INTO settings (key, value) VALUES ('default_units', 'imperial');
`);
db.prepare(
`UPDATE profile SET
name = ?, sex = ?, age = ?, height_cm = ?, weight_kg = ?, goal = ?,
rate_lb_week = ?, diet = ?, protein_target_g = ?, onboarded = ?, updated_at = ?
WHERE id = 1`
).run(
p.name,
p.sex,
p.age,
p.height_cm,
p.weight_kg,
p.goal,
p.rate_lb_week,
p.diet,
p.protein_target_g ?? null,
p.onboarded ? 1 : 0,
new Date().toISOString()
);
db.prepare(`INSERT OR REPLACE INTO settings (key, value) VALUES ('pound_week_max', ?)`).run(String(p.poundWeekMax ?? 7));
db.prepare(`INSERT OR REPLACE INTO settings (key, value) VALUES ('default_units', ?)`).run(p.units ?? 'imperial');
return getProfile();
}
module.exports = { db, DATA_DIR, getProfile, getSettings, updateProfile };
+142
View File
@@ -0,0 +1,142 @@
'use strict';
/**
* Energy maths for the tracker.
*
* Internal units are metric (kg, cm). The app stores weight in kg and height in cm,
* but exposes pounds/lbs and feet+inches in the API and UI, and accepts lbs/week as the
* goal rate.
*
* Burn model (an estimate, not a lab measurement):
* basal = BMR (Mifflin-St Jeor) x 1.2 for sedentary daily living
* steps = steps x body weight (kg) x 0.0005 (~0.04 kcal/step at 80 kg)
* workout= MET x 3.5 x body weight (kg) / 200 x minutes
* Intake target = basal + steps + workouts +/- the goal rate (3500 kcal per lb).
*/
const LB_PER_KG = 2.20462;
const KG_PER_LB = 1 / LB_PER_KG;
const IN_PER_CM = 1 / 2.54;
const CM_PER_IN = 2.54;
const IN_PER_FT = 12;
const KCAL_PER_LB = 3500;
const KCAL_PER_KG = KCAL_PER_LB * LB_PER_KG; // 7716.16...
const SEDENTARY_FACTOR = 1.2;
function clamp(n, min, max) {
return Math.min(Math.max(n, min), max);
}
/** Convert imperial height (feet, inches) and weight (pounds) to metric. */
function imperialToMetric({ feet = 0, inches = 0, pounds = 0 }) {
const totalInches = Math.max(0, Number(feet) * IN_PER_FT + Number(inches));
const cm = totalInches * CM_PER_IN;
const kg = Number(pounds) * KG_PER_LB;
return { heightCm: cm, weightKg: kg };
}
/** Convert metric back to imperial for display. */
function metricToImperial({ weightKg, heightCm }) {
const pounds = Math.round(Number(weightKg) * LB_PER_KG * 10) / 10;
const totalInches = Math.round(Number(heightCm) / CM_PER_IN);
const feet = Math.floor(totalInches / IN_PER_FT);
const inches = totalInches % IN_PER_FT;
return { pounds, feet, inches, totalInches };
}
/** Round a pounds/week value to the nearest 0.5 lb. */
function roundLbWeek(n) {
return Math.round(n * 2) / 2;
}
function bmrKcal({ sex, weightKg, heightCm, age }) {
const base = 10 * weightKg + 6.25 * heightCm - 5 * age;
return Math.round(Math.max(0, base + (sex === 'female' ? -161 : 5)));
}
function kcalFromSteps(steps, weightKg) {
return Math.round(clamp(Number(steps) || 0, 0, 200000) * (Number(weightKg) || 0) * 0.0005);
}
function kcalFromExercise({ met, minutes, weightKg }) {
const m = clamp(Number(met) || 0, 0, 30);
const mins = clamp(Number(minutes) || 0, 0, 1440);
return Math.round((m * 3.5 * (Number(weightKg) || 0) / 200) * mins);
}
function dailyTargets(profile, burn = {}) {
const weight = Number(profile.weight_kg) || 75;
const height = Number(profile.height_cm) || 175;
const age = Number(profile.age) || 30;
const sex = profile.sex === 'female' ? 'female' : 'male';
const bmr = bmrKcal({ sex, weightKg: weight, heightCm: height, age });
const basal = Math.round(bmr * SEDENTARY_FACTOR);
const steps = clamp(Number(burn.steps) || 0, 0, 200000);
const stepKcal = kcalFromSteps(steps, weight);
const exerciseKcal = Math.round(clamp(Number(burn.exerciseKcal) || 0, 0, 10000));
const totalBurn = basal + stepKcal + exerciseKcal;
const goal = ['lose', 'maintain', 'gain'].includes(profile.goal) ? profile.goal : 'maintain';
// Accept lbs/week (new) or kg/week (legacy). Internal deficit math uses kcal per kg.
const rateLbWeek = Number(profile.rate_lb_week);
const rateKgWeek = Number(profile.rate_kg_week);
let rateKg = null;
if (Number.isFinite(rateLbWeek) && rateLbWeek > 0) {
rateKg = rateLbWeek * KG_PER_LB;
} else if (Number.isFinite(rateKgWeek) && rateKgWeek > 0) {
rateKg = rateKgWeek;
}
rateKg = clamp(rateKg, 0, 1.5);
const adjust =
goal === 'lose' ? -Math.round(rateKg * KCAL_PER_KG / 7)
: goal === 'gain' ? Math.round(rateKg * KCAL_PER_KG / 7)
: 0;
const floor = sex === 'female' ? 1200 : 1500;
const targetKcal = Math.max(floor, Math.round(totalBurn + adjust));
const proteinTarget = Number(profile.protein_target_g)
|| Math.round(weight * (goal === 'lose' ? 2.0 : 1.6));
const fatTarget = Math.round((targetKcal * 0.3) / 9);
const carbsTarget = Math.max(
0,
Math.round((targetKcal - proteinTarget * 4 - fatTarget * 9) / 4)
);
const outRateLbWeek = rateKg > 0
? Math.round((rateKg / KG_PER_LB) * 2) / 2
: Math.round(rateKgWeek * 2) / 2;
return {
bmrKcal: bmr,
basalKcal: basal,
stepKcal,
exerciseKcal,
totalBurnKcal: totalBurn,
adjustKcal: adjust,
targetKcal,
rateLbWeek: outRateLbWeek,
protein_g: Math.round(proteinTarget),
carbs_g: carbsTarget,
fat_g: fatTarget,
};
}
module.exports = {
LB_PER_KG,
KG_PER_LB,
CM_PER_IN,
IN_PER_CM,
IN_PER_FT,
KCAL_PER_LB,
KCAL_PER_KG,
SEDENTARY_FACTOR,
imperialToMetric,
metricToImperial,
roundLbWeek,
bmrKcal,
kcalFromSteps,
kcalFromExercise,
dailyTargets,
};
+162
View File
@@ -0,0 +1,162 @@
'use strict';
/**
* Health Auto Export (iOS) REST automation adapter.
*
* Payload shape:
* { "data": { "metrics": [ { name: "step_count", data: [{ qty, date }] } ],
* "workouts": [ { id, name, start, end, duration, activeEnergyBurned } ] } }
*
* Dates use "yyyy-MM-dd HH:mm:ss Z"; the date part is already local to the
* phone, so it can be grouped directly. Workout `duration` is seconds in the
* v2 format (v1 omits it, so fall back to start/end).
*/
const WORKOUT_TYPES = {
running: { name: 'Running', met: 9.0 },
walking: { name: 'Walking', met: 4.3 },
cycling: { name: 'Cycling', met: 7.5 },
swimming: { name: 'Swimming', met: 6.0 },
hiking: { name: 'Hiking', met: 6.0 },
yoga: { name: 'Yoga', met: 2.5 },
rowing: { name: 'Rowing', met: 7.0 },
elliptical: { name: 'Elliptical', met: 5.0 },
dance: { name: 'Dance', met: 5.5 },
'cardio dance': { name: 'Dance', met: 5.5 },
hiit: { name: 'HIIT', met: 8.0 },
'high intensity interval training': { name: 'HIIT', met: 8.0 },
'traditional strength training': { name: 'Strength training', met: 5.0 },
'functional strength training': { name: 'Strength training', met: 5.0 },
'strength training': { name: 'Strength training', met: 5.0 },
'core training': { name: 'Core training', met: 3.5 },
flexibility: { name: 'Stretching', met: 2.3 },
pilates: { name: 'Pilates', met: 3.0 },
soccer: { name: 'Soccer', met: 7.0 },
basketball: { name: 'Basketball', met: 6.5 },
tennis: { name: 'Tennis', met: 7.3 },
golf: { name: 'Golf', met: 4.8 },
skiing: { name: 'Skiing', met: 7.0 },
snowboarding: { name: 'Snowboarding', met: 5.3 },
surfing: { name: 'Surfing', met: 5.0 },
climbing: { name: 'Climbing', met: 8.0 },
'stair climbing': { name: 'Stair climbing', met: 8.8 },
'jump rope': { name: 'Jump rope', met: 12.3 },
boxing: { name: 'Boxing', met: 7.8 },
'martial arts': { name: 'Martial arts', met: 10.3 },
'team sports': { name: 'Team sport', met: 7.0 },
other: { name: 'Workout', met: 6.0 },
};
function normalizeName(name) {
return String(name || '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
}
function titleCase(name) {
return String(name || '')
.replace(/\w\S*/g, (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
}
function localDay(value) {
const match = /^(\d{4}-\d{2}-\d{2})/.exec(String(value || ''));
return match ? match[1] : null;
}
function appleDate(value) {
if (typeof value !== 'string') return NaN;
const iso = value.trim().replace(' ', 'T').replace(/ ([+-]\d{2})(\d{2})$/, '$1:$2');
return Date.parse(iso);
}
function workoutMeta(name) {
const key = normalizeName(name);
if (WORKOUT_TYPES[key]) return WORKOUT_TYPES[key];
if (key.includes('strength')) return { name: 'Strength training', met: 5.0 };
if (key.includes('run')) return { name: 'Running', met: 9.0 };
if (key.includes('walk')) return { name: 'Walking', met: 4.3 };
if (key.includes('cycl') || key.includes('bike')) return { name: 'Cycling', met: 7.5 };
return { name: titleCase(name) || 'Workout', met: 6.0 };
}
function durationMinutes(workout) {
const seconds = Number(workout.duration);
if (Number.isFinite(seconds) && seconds > 0) return seconds / 60;
const start = appleDate(workout.start);
const end = appleDate(workout.end);
if (Number.isFinite(start) && Number.isFinite(end) && end > start) {
return (end - start) / 60000;
}
return 0;
}
function activeKcal(workout) {
const fields = [workout.activeEnergyBurned, workout.activeEnergy, workout.totalEnergy];
for (const field of fields) {
const qty = Number(field && field.qty);
if (Number.isFinite(qty) && qty > 0) return qty;
}
return 0;
}
function intensityMet(workout) {
const qty = Number(workout.intensity && workout.intensity.qty);
return Number.isFinite(qty) && qty >= 1 && qty <= 25 ? qty : null;
}
function parseHealthAutoExport(payload) {
const root = payload && typeof payload === 'object' ? payload : {};
const data = root.data && typeof root.data === 'object' ? root.data : root;
const stepDays = new Map();
const metrics = Array.isArray(data.metrics) ? data.metrics : [];
for (const metric of metrics) {
const name = String((metric && metric.name) || '').toLowerCase().replace(/[^a-z0-9]+/g, '_');
if (name !== 'step_count') continue;
const points = Array.isArray(metric.data) ? metric.data : [];
for (const point of points) {
const day = localDay(point && point.date);
const qty = Number(point && point.qty);
if (!day || !Number.isFinite(qty) || qty <= 0) continue;
stepDays.set(day, (stepDays.get(day) || 0) + qty);
}
}
const rawWorkouts = Array.isArray(data.workouts) ? data.workouts : [];
const workouts = [];
const seen = new Set();
for (const workout of rawWorkouts) {
if (!workout || typeof workout !== 'object') continue;
const day = localDay(workout.start);
if (!day) continue;
const minutes = durationMinutes(workout);
if (!(minutes > 0)) continue;
const meta = workoutMeta(workout.name);
const externalId = workout.id
? `hae:${String(workout.id).slice(0, 120)}`
: `hae:${normalizeName(workout.name)}:${workout.start}`;
if (seen.has(externalId)) continue;
seen.add(externalId);
workouts.push({
externalId,
date: day,
name: meta.name,
minutes: Math.round(minutes * 10) / 10,
kcal: Math.round(activeKcal(workout)),
met: intensityMet(workout) || meta.met,
});
}
return {
days: Array.from(stepDays, ([date, steps]) => ({ date, steps: Math.round(steps) })),
workouts,
};
}
module.exports = { parseHealthAutoExport, workoutMeta };
+57
View File
@@ -0,0 +1,57 @@
'use strict';
const path = require('node:path');
const express = require('express');
const api = require('./router');
const app = express();
app.disable('x-powered-by');
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'same-origin');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
next();
});
app.use(express.json({ limit: '5mb' }));
app.use('/api', api);
// Serve the barcode scanner bundle from node_modules (no frontend build step).
app.use(
'/vendor/zxing',
express.static(path.join(__dirname, '..', 'node_modules', '@zxing', 'library', 'umd'), {
maxAge: '30d',
immutable: true,
})
);
app.use(
express.static(path.join(__dirname, '..', 'public'), {
maxAge: '10m',
setHeaders(res, filePath) {
if (filePath.endsWith('.html')) res.setHeader('Cache-Control', 'no-cache');
},
})
);
app.use((req, res, next) => {
if (req.method !== 'GET' && req.method !== 'HEAD') return next();
if (path.extname(req.path)) return next();
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
app.use((req, res) => {
res.status(404).json({ error: 'Not found' });
});
app.use((err, req, res, next) => {
const status = Number(err.status) >= 400 && Number(err.status) < 600 ? Number(err.status) : 500;
if (status >= 500) console.error(err);
res.status(status).json({ error: err.message || 'Unexpected error' });
});
const port = Number(process.env.PORT) || Number(process.env.APP_PORT) || 31490;
app.listen(port, '0.0.0.0', () => {
console.log(`Counter listening on http://0.0.0.0:${port} (data: ${process.env.DATA_DIR || './data'})`);
});
+163
View File
@@ -0,0 +1,163 @@
'use strict';
const { db } = require('./db');
const USER_AGENT = 'Counter/1.0 (self-hosted calorie tracker)';
const BASE_URL = (process.env.OFF_BASE_URL || 'https://world.openfoodfacts.org').replace(/\/$/, '');
const CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
const FIELDS = [
'code', 'product_name', 'product_name_en', 'generic_name', 'brands',
'image_front_small_url', 'image_front_url', 'serving_size', 'serving_quantity',
'quantity', 'nutriments',
].join(',');
function serviceError(message, cause) {
const err = new Error(message);
err.status = 502;
if (cause) err.cause = cause;
return err;
}
async function getJson(url) {
let res;
try {
res = await fetch(url, {
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' },
signal: AbortSignal.timeout(Number(process.env.OFF_TIMEOUT_MS) || 8000),
});
} catch (err) {
throw serviceError('Could not reach Open Food Facts. Check the connection and try again.', err);
}
if (!res.ok) throw serviceError(`Open Food Facts responded with HTTP ${res.status}.`);
try {
return await res.json();
} catch (err) {
throw serviceError('Open Food Facts returned a response we could not read.', err);
}
}
function toNumber(value) {
const n = Number(value);
return Number.isFinite(n) && n > 0 ? n : 0;
}
function round1(n) {
return Math.round(n * 10) / 10;
}
function normalizeProduct(product) {
if (!product || typeof product !== 'object') return null;
const nut = product.nutriments && typeof product.nutriments === 'object' ? product.nutriments : {};
const energyKj = toNumber(nut.energy_100g) || toNumber(nut['energy-kj_100g']);
let kcal100 = toNumber(nut['energy-kcal_100g']);
if (!kcal100 && energyKj) kcal100 = energyKj / 4.184;
if (!kcal100) return null;
const name = [product.product_name_en, product.product_name, product.generic_name]
.find((value) => typeof value === 'string' && value.trim()) || '';
const code = String(product.code || '').trim();
if (!name && !code) return null;
const sodium100g = toNumber(nut.sodium_100g) || toNumber(nut.salt_100g) / 2.5;
const servingGrams = toNumber(product.serving_quantity) || parseFloat(product.serving_quantity) || null;
return {
code,
name: (name || `Product ${code}`).trim().slice(0, 160),
brand: String(product.brands || '').split(',')[0].trim().slice(0, 80),
image: product.image_front_small_url || product.image_front_url || null,
quantity: product.quantity || null,
servingLabel: product.serving_size || null,
servingGrams: servingGrams && servingGrams > 0 ? round1(servingGrams) : null,
per100g: {
kcal: Math.round(kcal100),
protein_g: round1(toNumber(nut.proteins_100g)),
carbs_g: round1(toNumber(nut.carbohydrates_100g)),
fat_g: round1(toNumber(nut.fat_100g)),
fiber_g: round1(toNumber(nut.fiber_100g)),
sugar_g: round1(toNumber(nut.sugars_100g)),
sodium_mg: Math.round(sodium100g * 1000),
},
source: 'Open Food Facts',
};
}
function readCache(code) {
const row = db.prepare('SELECT payload, fetched_at FROM food_cache WHERE barcode = ?').get(code);
if (!row) return null;
let payload;
try {
payload = JSON.parse(row.payload);
} catch {
return null;
}
const age = Date.now() - Date.parse(row.fetched_at);
return { payload, stale: !(Number.isFinite(age) && age < CACHE_TTL_MS) };
}
function writeCache(code, product) {
db.prepare(
`INSERT INTO food_cache (barcode, payload, fetched_at) VALUES (?, ?, ?)
ON CONFLICT(barcode) DO UPDATE SET payload = excluded.payload, fetched_at = excluded.fetched_at`
).run(code, JSON.stringify(product), new Date().toISOString());
}
async function getProduct(barcode) {
const code = String(barcode || '').trim();
if (!/^\d{6,14}$/.test(code)) {
const err = new Error('A barcode is 6 to 14 digits.');
err.status = 400;
throw err;
}
const cached = readCache(code);
if (cached && !cached.stale) {
const product = normalizeProduct(cached.payload);
if (product) return product;
}
try {
const data = await getJson(
`${BASE_URL}/api/v2/product/${encodeURIComponent(code)}.json?fields=${FIELDS}`
);
if (!data || data.status !== 1 || !data.product) return null;
writeCache(code, data.product);
return normalizeProduct(data.product);
} catch (err) {
// A slightly stale cached product beats a failed scan.
if (cached) {
const product = normalizeProduct(cached.payload);
if (product) return product;
}
throw err;
}
}
async function searchFoods(query) {
const url = new URL('/cgi/search.pl', BASE_URL);
url.searchParams.set('search_terms', query);
url.searchParams.set('search_simple', '1');
url.searchParams.set('action', 'process');
url.searchParams.set('json', '1');
url.searchParams.set('page_size', '24');
url.searchParams.set('fields', FIELDS);
const data = await getJson(url.toString());
const raw = Array.isArray(data.products) ? data.products : [];
const seen = new Set();
const products = [];
for (const item of raw) {
const product = normalizeProduct(item);
if (!product || !product.code || seen.has(product.code)) continue;
seen.add(product.code);
products.push(product);
}
return products;
}
module.exports = { getProduct, searchFoods, normalizeProduct, getJson };
+87
View File
@@ -0,0 +1,87 @@
'use strict';
const SPLIT = { breakfast: 0.25, lunch: 0.35, dinner: 0.3, snack: 0.1 };
function round1(n) {
return Math.round(n * 10) / 10;
}
// Stable pseudo-random jitter so plans vary by day without changing on refresh.
function hash(str) {
let h = 2166136261;
for (let i = 0; i < str.length; i += 1) {
h ^= str.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return Math.abs(h);
}
function styleAllows(recipe, style) {
if (!style || style === 'any') return true;
if (style === 'high_protein') {
return recipe.tags.includes('high_protein') || recipe.protein_g >= 25;
}
if (style === 'vegetarian') {
return recipe.tags.includes('vegetarian') || recipe.tags.includes('vegan');
}
return recipe.tags.includes(style);
}
function totalsOf(items) {
const total = { kcal: 0, protein_g: 0, carbs_g: 0, fat_g: 0 };
for (const item of items) {
total.kcal += item.kcal;
total.protein_g += item.protein_g;
total.carbs_g += item.carbs_g;
total.fat_g += item.fat_g;
}
return {
kcal: Math.round(total.kcal),
protein_g: round1(total.protein_g),
carbs_g: round1(total.carbs_g),
fat_g: round1(total.fat_g),
};
}
/**
* Pick one recipe per meal slot that best fits the energy and protein budget.
* Falls back to any recipe in a slot when the style filters everything out.
*/
function generatePlan({ date = '', targetKcal = 2000, proteinTarget = 120, style = 'any', recipes }) {
const used = new Set();
const items = [];
for (const [meal, share] of Object.entries(SPLIT)) {
const kcalTarget = targetKcal * share;
const proteinForMeal = proteinTarget * share;
let pool = recipes.filter(
(recipe) => recipe.meal === meal && !used.has(recipe.id) && styleAllows(recipe, style)
);
if (!pool.length) {
pool = recipes.filter((recipe) => recipe.meal === meal && !used.has(recipe.id));
}
if (!pool.length) continue;
let best = null;
for (const recipe of pool) {
const jitter = (hash(`${date}:${recipe.id}`) % 21) / 10;
const score =
(Math.abs(recipe.kcal - kcalTarget) / Math.max(kcalTarget, 1)) * 100 +
Math.max(0, proteinForMeal - recipe.protein_g) * 1.5 +
jitter;
if (!best || score < best.score) best = { recipe, score };
}
used.add(best.recipe.id);
items.push(best.recipe);
}
return {
style,
items: items.map((recipe, index) => ({ ...recipe, sort: index })),
totals: totalsOf(items),
};
}
module.exports = { SPLIT, generatePlan, styleAllows, totalsOf };
+574
View File
@@ -0,0 +1,574 @@
'use strict';
const crypto = require('node:crypto');
const express = require('express');
const { db, getProfile, updateProfile } = require('./db');
const nutrition = require('./nutrition');
const { kcalFromSteps, kcalFromExercise, dailyTargets, imperialToMetric, roundLbWeek, roundLb } = require('./energy');
const { generatePlan } = require('./planner');
const { parseHealthAutoExport } = require('./health-auto-export');
const { RECIPES, MET_PRESETS, STYLES } = require('./seed');
const { version } = require('../package.json');
const router = express.Router();
const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'];
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
function isDate(value) {
if (typeof value !== 'string' || !DATE_RE.test(value)) return false;
const parsed = new Date(`${value}T00:00:00Z`);
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
}
function bad(res, message, status = 400) {
return res.status(status).json({ error: message });
}
function round1(n) {
return Math.round(n * 10) / 10;
}
function roundLb(n) {
return Math.round(Number(n) * 10) / 10;
}
function number(value, { min = 0, max = 100000, fallback = 0 } = {}) {
const n = Number(value);
if (!Number.isFinite(n)) return fallback;
return Math.min(Math.max(n, min), max);
}
function text(value, max = 120) {
return typeof value === 'string' ? value.trim().slice(0, max) : '';
}
function serverToday() {
return new Intl.DateTimeFormat('en-CA', {
timeZone: process.env.TZ || undefined,
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(new Date());
}
function totalsOf(entries) {
const total = { kcal: 0, protein_g: 0, carbs_g: 0, fat_g: 0, fiber_g: 0, sugar_g: 0, sodium_mg: 0 };
for (const entry of entries) {
total.kcal += Number(entry.kcal) || 0;
total.protein_g += Number(entry.protein_g) || 0;
total.carbs_g += Number(entry.carbs_g) || 0;
total.fat_g += Number(entry.fat_g) || 0;
total.fiber_g += Number(entry.fiber_g) || 0;
total.sugar_g += Number(entry.sugar_g) || 0;
total.sodium_mg += Number(entry.sodium_mg) || 0;
}
return {
kcal: Math.round(total.kcal),
protein_g: round1(total.protein_g),
carbs_g: round1(total.carbs_g),
fat_g: round1(total.fat_g),
fiber_g: round1(total.fiber_g),
sugar_g: round1(total.sugar_g),
sodium_mg: Math.round(total.sodium_mg),
};
}
function readPlan(date) {
const rows = db.prepare('SELECT * FROM plan_items WHERE date = ? ORDER BY sort, id').all(date);
if (!rows.length) return null;
const items = rows.map((row) => {
const recipe = RECIPES.find((r) => r.id === row.recipe_id);
return {
...row,
ingredients: recipe ? recipe.ingredients : [],
prep: recipe ? recipe.prep : null,
tags: recipe ? recipe.tags : [],
};
});
return {
style: rows[0].style,
items,
totals: {
kcal: Math.round(items.reduce((sum, item) => sum + item.kcal, 0)),
protein_g: round1(items.reduce((sum, item) => sum + item.protein_g, 0)),
carbs_g: round1(items.reduce((sum, item) => sum + item.carbs_g, 0)),
fat_g: round1(items.reduce((sum, item) => sum + item.fat_g, 0)),
},
};
}
function buildDay(date) {
const profile = getProfile();
const entries = db.prepare('SELECT * FROM entries WHERE date = ? ORDER BY id').all(date);
const activities = db.prepare('SELECT * FROM activities WHERE date = ? ORDER BY id').all(date);
const weight = Number(profile.weight_kg) || 75;
const steps = activities
.filter((activity) => activity.type === 'steps')
.reduce((sum, activity) => sum + (Number(activity.steps) || 0), 0);
const activitiesOut = activities.map((activity) => {
const stored = Number(activity.kcal) || 0;
let kcal;
if (activity.type === 'steps') {
kcal = kcalFromSteps(activity.steps, weight);
} else if (activity.source !== 'manual' && stored > 0) {
// Imported workouts carry measured calories; do not re-estimate them.
kcal = Math.round(stored);
} else {
kcal = kcalFromExercise({ met: activity.met, minutes: activity.minutes, weightKg: weight });
}
return { ...activity, kcal };
});
const exerciseKcal = activitiesOut
.filter((activity) => activity.type === 'exercise')
.reduce((sum, activity) => sum + activity.kcal, 0);
const totals = totalsOf(entries);
const targets = dailyTargets(profile, { steps, exerciseKcal });
return {
date,
profile,
entries,
activities: activitiesOut,
steps,
totals,
targets,
remainingKcal: targets.targetKcal - totals.kcal,
plan: readPlan(date),
};
}
function replaceSteps(date, steps, source = 'manual') {
const weight = Number(getProfile().weight_kg) || 75;
db.prepare("DELETE FROM activities WHERE date = ? AND type = 'steps'").run(date);
db.prepare(
"INSERT INTO activities (date, type, name, steps, kcal, source, created_at) VALUES (?, 'steps', 'Steps', ?, ?, ?, ?)"
).run(date, steps, kcalFromSteps(steps, weight), source, new Date().toISOString());
}
function importWorkouts(workouts, source) {
const now = new Date().toISOString();
const weight = Number(getProfile().weight_kg) || 75;
const insert = db.prepare(
`INSERT OR IGNORE INTO activities
(date, type, name, minutes, met, kcal, source, external_id, created_at)
VALUES (?, 'exercise', ?, ?, ?, ?, ?, ?, ?)`
);
let imported = 0;
for (const workout of workouts) {
if (!workout || !isDate(workout.date)) continue;
const minutes = number(workout.minutes, { min: 0.1, max: 1440 });
if (minutes <= 0) continue;
const met = number(workout.met, { min: 1, max: 30, fallback: 6 });
const name = text(workout.name, 80) || 'Workout';
const providedKcal = number(workout.kcal, { max: 10000 });
const kcal = providedKcal > 0
? Math.round(providedKcal)
: kcalFromExercise({ met, minutes, weightKg: weight });
const externalId = text(workout.externalId, 140) || `${workout.date}:${name}:${minutes}`;
const result = insert.run(workout.date, name, minutes, met, kcal, source, externalId, now);
if (result.changes > 0) imported += 1;
}
return imported;
}
function requireIngestToken(req, res, next) {
const token = process.env.INGEST_TOKEN;
if (!token) {
return bad(res, 'Ingest is disabled. Set INGEST_TOKEN on the server to enable it.', 403);
}
const provided = String(req.get('authorization') || '').replace(/^Bearer\s+/i, '').trim();
const a = Buffer.from(provided);
const b = Buffer.from(token);
if (!provided || a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return bad(res, 'Unauthorized', 401);
}
next();
}
// ---------------------------------------------------------------- meta/profile
router.get('/health', (req, res) => {
res.json({ ok: true, version, uptime: Math.round(process.uptime()) });
});
router.get('/meta', (req, res) => {
const settings = require('./db').getSettings();
const imperial = settings.default_units === 'imperial';
res.json({
metPresets: MET_PRESETS,
styles: STYLES,
meals: MEALS,
source: 'Open Food Facts',
stepIngest: Boolean(process.env.INGEST_TOKEN),
units: {
weight: imperial ? 'lb' : 'kg',
height: imperial ? 'ft_in' : 'cm',
goalRate: imperial ? 'lb_week' : 'kg_week',
protein: 'g',
},
});
});
router.get('/profile', (req, res) => {
const profile = getProfile();
const targets = dailyTargets(profile);
// Expose imperial equivalents for UIs that use pounds/feet/inches.
const imperial = metricToImperial({
weightKg: profile.weight_kg,
heightCm: profile.height_cm,
});
res.json({
profile,
targets,
imperial: {
pounds: imperial.pounds,
feet: imperial.feet,
inches: imperial.inches,
totalInches: imperial.totalInches,
},
});
});
router.put('/profile', (req, res) => {
const body = req.body || {};
// Accept imperial inputs: feet/inches and pounds, plus lbs/week goal rate.
const metric = imperialToMetric({
feet: number(body.feet, { min: 0, max: 8, fallback: 0 }),
inches: number(body.inches, { min: 0, max: 11, fallback: 0 }),
pounds: number(body.pounds, { min: 80, max: 660, fallback: 0 }),
});
const weightKg = body.weight_kg != null
? round1(number(body.weight_kg, { min: 30, max: 300, fallback: 75 }))
: round1(metric.weightKg || 75);
const heightCm = body.height_cm != null
? round1(number(body.height_cm, { min: 100, max: 250, fallback: 175 }))
: round1(metric.heightCm || 175);
// Goal rate: accept lbs/week (new default) or kg/week (legacy).
const rateLbWeekRaw = number(body.rate_lb_week != null ? body.rate_lb_week : body.rate_kg_week, {
min: 0,
max: 7,
fallback: 0.5,
});
const rateLbWeek = roundLbWeek(rateLbWeekRaw);
const profile = updateProfile({
name: text(body.name, 60),
sex: body.sex === 'female' ? 'female' : 'male',
age: Math.round(number(body.age, { min: 13, max: 120, fallback: 30 })),
height_cm: heightCm,
weight_kg: weightKg,
goal: ['lose', 'maintain', 'gain'].includes(body.goal) ? body.goal : 'maintain',
rate_lb_week: rateLbWeek,
diet: STYLES.some((style) => style.id === body.diet) ? body.diet : 'any',
protein_target_g:
body.protein_target_g === '' || body.protein_target_g == null
? null
: Math.round(number(body.protein_target_g, { min: 0, max: 400 })),
onboarded: 1,
});
res.json({ profile, targets: dailyTargets(profile) });
});
// ---------------------------------------------------------------------- days
router.get('/day/:date', (req, res) => {
if (!isDate(req.params.date)) return bad(res, 'date must be YYYY-MM-DD');
res.json(buildDay(req.params.date));
});
// -------------------------------------------------------------------- entries
router.post('/entries', (req, res) => {
const body = req.body || {};
if (!isDate(body.date)) return bad(res, 'date is required as YYYY-MM-DD');
const meal = MEALS.includes(body.meal) ? body.meal : 'snack';
const name = text(body.name, 160);
if (!name) return bad(res, 'name is required');
let grams = null;
let kcal;
let protein = 0;
let carbs = 0;
let fat = 0;
let fiber = 0;
let sugar = 0;
let sodium = 0;
let source = 'manual';
if (body.per100g && typeof body.per100g === 'object' && body.grams != null) {
grams = round1(number(body.grams, { min: 0, max: 5000 }));
if (grams <= 0) return bad(res, 'grams must be greater than 0');
const factor = grams / 100;
const per = body.per100g;
kcal = number(per.kcal, { max: 900 }) * factor;
protein = number(per.protein_g, { max: 100 }) * factor;
carbs = number(per.carbs_g, { max: 100 }) * factor;
fat = number(per.fat_g, { max: 100 }) * factor;
fiber = number(per.fiber_g, { max: 100 }) * factor;
sugar = number(per.sugar_g, { max: 100 }) * factor;
sodium = number(per.sodium_mg, { max: 100000 }) * factor;
source = 'openfoodfacts';
} else {
kcal = number(body.kcal, { max: 5000 });
protein = number(body.protein_g, { max: 500 });
carbs = number(body.carbs_g, { max: 500 });
fat = number(body.fat_g, { max: 500 });
fiber = number(body.fiber_g, { max: 500 });
sugar = number(body.sugar_g, { max: 500 });
sodium = number(body.sodium_mg, { max: 100000 });
}
const result = db.prepare(
`INSERT INTO entries
(date, meal, name, brand, barcode, grams, kcal, protein_g, carbs_g, fat_g,
fiber_g, sugar_g, sodium_mg, image_url, source, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
).run(
body.date, meal, name,
text(body.brand, 80) || null,
/^\d{6,14}$/.test(String(body.barcode || '')) ? String(body.barcode) : null,
grams,
Math.round(kcal),
round1(protein), round1(carbs), round1(fat), round1(fiber), round1(sugar),
Math.round(sodium),
typeof body.image_url === 'string' && /^https?:\/\//.test(body.image_url) ? body.image_url.slice(0, 400) : null,
source,
new Date().toISOString()
);
const entry = db.prepare('SELECT * FROM entries WHERE id = ?').get(result.lastInsertRowid);
res.status(201).json({ entry, day: buildDay(body.date) });
});
router.delete('/entries/:id', (req, res) => {
const id = Number(req.params.id);
const row = db.prepare('SELECT date FROM entries WHERE id = ?').get(id);
if (!row) return bad(res, 'Entry not found', 404);
db.prepare('DELETE FROM entries WHERE id = ?').run(id);
res.json({ day: buildDay(row.date) });
});
// ----------------------------------------------------------------- activities
router.post('/activities', (req, res) => {
const body = req.body || {};
if (!isDate(body.date)) return bad(res, 'date is required as YYYY-MM-DD');
if (body.type === 'steps') {
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
replaceSteps(body.date, steps);
return res.status(201).json({ day: buildDay(body.date) });
}
if (body.type !== 'exercise') return bad(res, 'type must be "steps" or "exercise"');
const minutes = number(body.minutes, { min: 1, max: 1440 });
if (minutes <= 0) return bad(res, 'minutes must be greater than 0');
const met = number(body.met, { min: 1, max: 30, fallback: 5 });
const name = text(body.name, 80) || 'Exercise';
const weight = Number(getProfile().weight_kg) || 75;
db.prepare(
`INSERT INTO activities (date, type, name, minutes, met, kcal, created_at)
VALUES (?, 'exercise', ?, ?, ?, ?, ?)`
).run(body.date, name, minutes, met, kcalFromExercise({ met, minutes, weightKg: weight }), new Date().toISOString());
res.status(201).json({ day: buildDay(body.date) });
});
router.delete('/activities/:id', (req, res) => {
const id = Number(req.params.id);
const row = db.prepare('SELECT date FROM activities WHERE id = ?').get(id);
if (!row) return bad(res, 'Activity not found', 404);
db.prepare('DELETE FROM activities WHERE id = ?').run(id);
res.json({ day: buildDay(row.date) });
});
// Push steps from a phone shortcut. Requires INGEST_TOKEN.
router.post('/ingest/steps', requireIngestToken, (req, res) => {
const body = req.body || {};
const date = body.date || serverToday();
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
if (steps <= 0) return bad(res, 'steps must be a positive number');
replaceSteps(date, steps, 'shortcut');
res.json({ ok: true, date, steps });
});
// Push steps and workouts from a phone shortcut (Apple Health via Shortcuts).
router.post('/ingest/health', requireIngestToken, (req, res) => {
const body = req.body || {};
const date = body.date || serverToday();
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const steps = Math.round(number(body.steps, { min: 0, max: 200000 }));
const workouts = Array.isArray(body.workouts) ? body.workouts.slice(0, 50) : [];
db.exec('BEGIN');
try {
if (steps > 0) replaceSteps(date, steps, 'shortcut');
const imported = importWorkouts(
workouts.map((workout) => ({ ...workout, date: workout.date || date })),
'shortcut'
);
db.exec('COMMIT');
res.json({ ok: true, date, steps, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// Health Auto Export (iOS) REST automation. Handles metrics and/or workouts.
router.post('/ingest/health-auto-export', requireIngestToken, (req, res) => {
const parsed = parseHealthAutoExport(req.body || {});
const days = parsed.days.filter((day) => isDate(day.date));
db.exec('BEGIN');
try {
for (const day of days) {
replaceSteps(day.date, day.steps, 'health-auto-export');
}
const imported = importWorkouts(parsed.workouts, 'health-auto-export');
db.exec('COMMIT');
res.json({ ok: true, stepsDays: days.length, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// Import a parsed Apple Health export from the web app (same-origin, no token).
router.post('/import/apple-health', (req, res) => {
const body = req.body || {};
const days = Array.isArray(body.days) ? body.days.slice(0, 3650) : [];
const workouts = Array.isArray(body.workouts) ? body.workouts.slice(0, 5000) : [];
db.exec('BEGIN');
try {
let stepsDays = 0;
for (const day of days) {
if (!day || !isDate(day.date)) continue;
const steps = Math.round(number(day.steps, { min: 0, max: 200000 }));
if (steps <= 0) continue;
replaceSteps(day.date, steps, 'apple_health');
stepsDays += 1;
}
const imported = importWorkouts(workouts, 'apple_health');
db.exec('COMMIT');
res.json({ stepsDays, workouts: imported });
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
});
// -------------------------------------------------------------------- planner
router.post('/plan/:date', (req, res) => {
const date = req.params.date;
if (!isDate(date)) return bad(res, 'date must be YYYY-MM-DD');
const body = req.body || {};
const profile = getProfile();
const requested = body.style;
const style = STYLES.some((s) => s.id === requested)
? requested
: STYLES.some((s) => s.id === profile.diet)
? profile.diet
: 'any';
const day = buildDay(date);
const plan = generatePlan({
date,
targetKcal: day.targets.targetKcal,
proteinTarget: day.targets.protein_g,
style,
recipes: RECIPES,
});
const now = new Date().toISOString();
const insert = db.prepare(
`INSERT INTO plan_items
(date, meal, recipe_id, name, kcal, protein_g, carbs_g, fat_g, servings, style, sort, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)`
);
db.exec('BEGIN');
try {
db.prepare('DELETE FROM plan_items WHERE date = ?').run(date);
plan.items.forEach((recipe, index) => {
insert.run(
date, recipe.meal, recipe.id, recipe.name, recipe.kcal, recipe.protein_g,
recipe.carbs_g, recipe.fat_g, style, index, now
);
});
db.exec('COMMIT');
} catch (err) {
db.exec('ROLLBACK');
throw err;
}
res.status(201).json({ plan: readPlan(date), targets: day.targets });
});
router.delete('/plan/:date', (req, res) => {
if (!isDate(req.params.date)) return bad(res, 'date must be YYYY-MM-DD');
db.prepare('DELETE FROM plan_items WHERE date = ?').run(req.params.date);
res.json({ day: buildDay(req.params.date) });
});
router.post('/plan/items/:id/log', (req, res) => {
const id = Number(req.params.id);
const item = db.prepare('SELECT * FROM plan_items WHERE id = ?').get(id);
if (!item) return bad(res, 'Plan item not found', 404);
db.prepare(
`INSERT INTO entries
(date, meal, name, grams, kcal, protein_g, carbs_g, fat_g, fiber_g, sugar_g, sodium_mg, source, created_at)
VALUES (?, ?, ?, NULL, ?, ?, ?, ?, 0, 0, 0, 'plan', ?)`
).run(
item.date, item.meal, item.name, item.kcal, item.protein_g,
item.carbs_g, item.fat_g, new Date().toISOString()
);
db.prepare('DELETE FROM plan_items WHERE id = ?').run(id);
res.json({ day: buildDay(item.date) });
});
// ----------------------------------------------------------------------- food
router.get('/foods/barcode/:code', async (req, res) => {
const product = await nutrition.getProduct(req.params.code);
if (!product) return bad(res, 'No product with that barcode in Open Food Facts.', 404);
res.json({ product });
});
router.get('/foods/search', async (req, res) => {
const query = text(req.query.q, 100);
if (query.length < 2) return bad(res, 'Search needs at least 2 characters.');
const products = await nutrition.searchFoods(query);
res.json({ products, query });
});
module.exports = router;
+227
View File
@@ -0,0 +1,227 @@
'use strict';
/**
* Built-in meal library used by the planner. Values are per serving and are
* approximations for planning, not a nutritional database. Log real products
* (or your own cooking) for accurate tracking.
*/
const RECIPES = [
// Breakfast
{
id: 'greek-yogurt-bowl', meal: 'breakfast', name: 'Greek yogurt berry bowl',
kcal: 380, protein_g: 28, carbs_g: 45, fat_g: 10,
tags: ['vegetarian', 'high_protein', 'quick'], prep: 5,
ingredients: ['200 g Greek yogurt', '1 cup mixed berries', '30 g granola', '1 tsp honey'],
},
{
id: 'egg-white-omelet', meal: 'breakfast', name: 'Veggie omelet with toast',
kcal: 320, protein_g: 27, carbs_g: 28, fat_g: 11,
tags: ['vegetarian', 'high_protein', 'quick'], prep: 10,
ingredients: ['3 eggs + 2 egg whites', 'Spinach, peppers, onion', '1 slice whole-grain toast'],
},
{
id: 'overnight-oats', meal: 'breakfast', name: 'Overnight oats with chia and banana',
kcal: 420, protein_g: 15, carbs_g: 62, fat_g: 13,
tags: ['vegetarian', 'quick'], prep: 5,
ingredients: ['50 g rolled oats', '200 ml milk', '1 tbsp chia', '1 banana'],
},
{
id: 'tofu-scramble', meal: 'breakfast', name: 'Tofu scramble with spinach',
kcal: 350, protein_g: 24, carbs_g: 18, fat_g: 20,
tags: ['vegan', 'high_protein'], prep: 12,
ingredients: ['200 g firm tofu', 'Spinach', 'Turmeric, nutritional yeast', '1 slice rye bread'],
},
{
id: 'pb-smoothie', meal: 'breakfast', name: 'Peanut butter banana smoothie',
kcal: 400, protein_g: 20, carbs_g: 45, fat_g: 16,
tags: ['vegan', 'quick'], prep: 5,
ingredients: ['1 banana', '2 tbsp peanut butter', '300 ml soy milk', '1 scoop oats'],
},
{
id: 'salmon-bagel', meal: 'breakfast', name: 'Smoked salmon bagel',
kcal: 450, protein_g: 25, carbs_g: 50, fat_g: 16,
tags: ['quick'], prep: 6,
ingredients: ['1 bagel', '60 g smoked salmon', 'Light cream cheese', 'Capers, red onion'],
},
{
id: 'protein-pancakes', meal: 'breakfast', name: 'Protein pancakes with berries',
kcal: 430, protein_g: 32, carbs_g: 48, fat_g: 12,
tags: ['vegetarian', 'high_protein'], prep: 15,
ingredients: ['40 g oat flour', '1 scoop protein powder', '1 egg', 'Blueberries, maple syrup'],
},
// Lunch
{
id: 'chicken-quinoa-bowl', meal: 'lunch', name: 'Grilled chicken quinoa bowl',
kcal: 560, protein_g: 45, carbs_g: 55, fat_g: 16,
tags: ['high_protein'], prep: 20,
ingredients: ['150 g chicken breast', '1 cup cooked quinoa', 'Roast vegetables', 'Tahini drizzle'],
},
{
id: 'turkey-wrap', meal: 'lunch', name: 'Turkey avocado wrap',
kcal: 480, protein_g: 32, carbs_g: 42, fat_g: 20,
tags: ['quick'], prep: 8,
ingredients: ['1 whole-wheat tortilla', '100 g turkey', '1/2 avocado', 'Lettuce, tomato'],
},
{
id: 'lentil-soup', meal: 'lunch', name: 'Lentil and vegetable soup with a roll',
kcal: 420, protein_g: 22, carbs_g: 60, fat_g: 9,
tags: ['vegan'], prep: 30,
ingredients: ['1 cup lentils', 'Carrot, celery, onion, tomato', 'Vegetable stock', '1 whole-grain roll'],
},
{
id: 'chickpea-salad', meal: 'lunch', name: 'Chickpea salad with feta',
kcal: 450, protein_g: 20, carbs_g: 45, fat_g: 20,
tags: ['vegetarian', 'quick'], prep: 10,
ingredients: ['1 can chickpeas', 'Cucumber, tomato, red onion', '40 g feta', 'Lemon and olive oil'],
},
{
id: 'tuna-pasta', meal: 'lunch', name: 'Tuna pasta salad',
kcal: 520, protein_g: 34, carbs_g: 58, fat_g: 16,
tags: ['quick'], prep: 15,
ingredients: ['80 g dry pasta', '1 can tuna', 'Sweetcorn, peas', 'Light mayo and lemon'],
},
{
id: 'chicken-burrito-bowl', meal: 'lunch', name: 'Chicken burrito bowl',
kcal: 620, protein_g: 42, carbs_g: 66, fat_g: 20,
tags: ['high_protein'], prep: 20,
ingredients: ['150 g chicken', '1 cup rice', 'Black beans', 'Salsa, cheese, lettuce'],
},
{
id: 'hummus-pita', meal: 'lunch', name: 'Hummus and veggie pita',
kcal: 440, protein_g: 16, carbs_g: 58, fat_g: 16,
tags: ['vegan', 'quick'], prep: 7,
ingredients: ['1 whole-wheat pita', '4 tbsp hummus', 'Cucumber, carrot, pepper', 'Olives'],
},
{
id: 'beef-broccoli', meal: 'lunch', name: 'Beef and broccoli rice bowl',
kcal: 580, protein_g: 40, carbs_g: 60, fat_g: 18,
tags: ['high_protein'], prep: 20,
ingredients: ['130 g lean beef', 'Broccoli, onion', 'Soy, ginger, garlic', '1 cup rice'],
},
// Dinner
{
id: 'baked-salmon', meal: 'dinner', name: 'Baked salmon with potatoes and greens',
kcal: 600, protein_g: 42, carbs_g: 45, fat_g: 26,
tags: [], prep: 30,
ingredients: ['160 g salmon', '250 g potatoes', 'Green beans', 'Lemon and dill'],
},
{
id: 'chicken-stirfry', meal: 'dinner', name: 'Chicken stir-fry with rice',
kcal: 560, protein_g: 40, carbs_g: 62, fat_g: 14,
tags: ['high_protein', 'quick'], prep: 18,
ingredients: ['150 g chicken thigh', 'Mixed stir-fry vegetables', 'Soy, ginger, sesame', '1 cup rice'],
},
{
id: 'black-bean-chili', meal: 'dinner', name: 'Black bean chili with rice',
kcal: 520, protein_g: 22, carbs_g: 78, fat_g: 12,
tags: ['vegan'], prep: 30,
ingredients: ['2 cans black beans', 'Tomatoes, onion, pepper', 'Cumin, chili, smoked paprika', '1 cup rice'],
},
{
id: 'turkey-meatballs', meal: 'dinner', name: 'Turkey meatballs with spaghetti',
kcal: 640, protein_g: 40, carbs_g: 72, fat_g: 18,
tags: ['high_protein'], prep: 30,
ingredients: ['150 g ground turkey', '80 g dry spaghetti', 'Tomato sauce', 'Parmesan, basil'],
},
{
id: 'shrimp-tacos', meal: 'dinner', name: 'Shrimp tacos',
kcal: 520, protein_g: 32, carbs_g: 48, fat_g: 20,
tags: ['quick'], prep: 15,
ingredients: ['150 g shrimp', '2 corn tortillas', 'Cabbage slaw', 'Yogurt-lime sauce'],
},
{
id: 'tofu-curry', meal: 'dinner', name: 'Tofu coconut curry with rice',
kcal: 580, protein_g: 22, carbs_g: 64, fat_g: 24,
tags: ['vegan'], prep: 25,
ingredients: ['200 g tofu', 'Light coconut milk', 'Curry paste, vegetables', '1 cup rice'],
},
{
id: 'steak-sweet-potato', meal: 'dinner', name: 'Steak, sweet potato and broccoli',
kcal: 650, protein_g: 45, carbs_g: 45, fat_g: 28,
tags: ['high_protein'], prep: 25,
ingredients: ['150 g sirloin', '1 large sweet potato', 'Broccoli', 'Butter and garlic'],
},
{
id: 'mushroom-risotto', meal: 'dinner', name: 'Mushroom risotto with peas',
kcal: 540, protein_g: 18, carbs_g: 78, fat_g: 16,
tags: ['vegetarian'], prep: 35,
ingredients: ['80 g arborio rice', 'Mushrooms', 'Peas, parmesan', 'Vegetable stock'],
},
// Snacks
{
id: 'apple-pb', meal: 'snack', name: 'Apple with peanut butter',
kcal: 220, protein_g: 6, carbs_g: 25, fat_g: 11,
tags: ['vegan', 'quick'], prep: 2,
ingredients: ['1 apple', '1.5 tbsp peanut butter'],
},
{
id: 'yogurt-honey', meal: 'snack', name: 'Greek yogurt with honey',
kcal: 160, protein_g: 15, carbs_g: 18, fat_g: 2,
tags: ['vegetarian', 'quick', 'high_protein'], prep: 2,
ingredients: ['150 g Greek yogurt', '1 tsp honey'],
},
{
id: 'protein-shake', meal: 'snack', name: 'Protein shake',
kcal: 180, protein_g: 30, carbs_g: 8, fat_g: 3,
tags: ['quick', 'high_protein'], prep: 3,
ingredients: ['1 scoop whey or plant protein', '300 ml milk or water'],
},
{
id: 'almonds', meal: 'snack', name: 'Handful of almonds',
kcal: 170, protein_g: 6, carbs_g: 6, fat_g: 15,
tags: ['vegan', 'quick'], prep: 1,
ingredients: ['28 g almonds'],
},
{
id: 'cottage-pineapple', meal: 'snack', name: 'Cottage cheese with pineapple',
kcal: 190, protein_g: 20, carbs_g: 18, fat_g: 3,
tags: ['vegetarian', 'quick', 'high_protein'], prep: 3,
ingredients: ['150 g cottage cheese', '1/2 cup pineapple'],
},
{
id: 'dark-chocolate', meal: 'snack', name: 'Dark chocolate square with tea',
kcal: 90, protein_g: 2, carbs_g: 10, fat_g: 6,
tags: ['vegetarian', 'quick'], prep: 2,
ingredients: ['20 g 85% dark chocolate', '1 cup tea'],
},
{
id: 'rice-cakes-avocado', meal: 'snack', name: 'Rice cakes with avocado',
kcal: 160, protein_g: 4, carbs_g: 18, fat_g: 9,
tags: ['vegan', 'quick'], prep: 4,
ingredients: ['2 rice cakes', '1/2 avocado', 'Chili flakes, salt'],
},
{
id: 'edamame', meal: 'snack', name: 'Salted edamame',
kcal: 190, protein_g: 17, carbs_g: 15, fat_g: 8,
tags: ['vegan', 'quick', 'high_protein'], prep: 5,
ingredients: ['1 cup shelled edamame', 'Sea salt'],
},
];
const MET_PRESETS = [
{ id: 'walk', label: 'Walking (brisk)', met: 4.3 },
{ id: 'run', label: 'Running', met: 9.0 },
{ id: 'cycle', label: 'Cycling', met: 7.5 },
{ id: 'swim', label: 'Swimming', met: 6.0 },
{ id: 'weights', label: 'Strength training', met: 5.0 },
{ id: 'hiit', label: 'HIIT', met: 8.0 },
{ id: 'yoga', label: 'Yoga', met: 2.5 },
{ id: 'hike', label: 'Hiking', met: 6.0 },
{ id: 'row', label: 'Rowing machine', met: 7.0 },
{ id: 'sport', label: 'Team sport', met: 7.0 },
{ id: 'dance', label: 'Dance', met: 5.5 },
{ id: 'elliptical', label: 'Elliptical', met: 5.0 },
];
const STYLES = [
{ id: 'any', label: 'Anything' },
{ id: 'vegetarian', label: 'Vegetarian' },
{ id: 'vegan', label: 'Vegan' },
{ id: 'high_protein', label: 'High protein' },
];
module.exports = { RECIPES, MET_PRESETS, STYLES };