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
+8
View File
@@ -0,0 +1,8 @@
node_modules
data
.git
.gitignore
.env
*.log
test
README.md
+9
View File
@@ -0,0 +1,9 @@
# Host port to publish the app on
APP_PORT=31490
# Timezone used for "today" when steps are pushed without a date
TZ=America/Denver
# Optional shared secret. When set, POST /api/ingest/steps requires
# "Authorization: Bearer <token>" and can be called from a phone shortcut.
INGEST_TOKEN=
+5
View File
@@ -0,0 +1,5 @@
node_modules/
data/
.env
*.log
.DS_Store
+24
View File
@@ -0,0 +1,24 @@
FROM node:24-alpine
ENV NODE_ENV=production \
APP_PORT=31490 \
DATA_DIR=/data
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm ci --omit=dev || npm install --omit=dev
COPY server ./server
COPY public ./public
RUN mkdir -p /data && chown -R node:node /data /app
USER node
EXPOSE 31490
VOLUME ["/data"]
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD node -e "fetch('http://127.0.0.1:31490/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
CMD ["node", "server/index.js"]
+158
View File
@@ -0,0 +1,158 @@
# Counter
A self-hosted calorie counter you run in Docker and use from your phone's browser.
- **Scan a barcode** with the camera (or take a photo) and pull calories and macros from [Open Food Facts](https://world.openfoodfacts.org). You can also search by name or type the numbers in yourself.
- **Track movement**: enter steps and workouts; the app estimates what you burned with MET values.
- **See the day** as one number: calories eaten minus target, with protein, carbs and fat bars.
- **Plan meals**: generates breakfast, lunch, dinner and a snack that fit your remaining budget, with vegan / vegetarian / high-protein styles.
- **Install to the home screen**: it is a PWA, so it opens full-screen like an app.
## Quick start
```bash
cp .env.example .env # optional: set TZ and INGEST_TOKEN
docker compose up -d --build
```
Open <http://localhost:31490> on the machine, or `http://<your-server-ip>:31490` on your phone (same network).
Data lives in the `counter-data` Docker volume (SQLite). To back it up:
```bash
docker run --rm -v counter-data:/data -v "$PWD":/backup alpine tar czf /backup/counter-backup.tgz -C /data .
```
## Using it on a phone
1. Find the host's LAN address (`hostname -I` on Linux, `ipconfig getifaddr en0` on macOS).
2. Open `http://THAT-IP:31490` in Safari or Chrome, then **Add to Home Screen**.
**Camera note:** browsers only allow live camera access on `https://` or `localhost`. Over plain `http://192.168.x.x:31490` the "Start camera" button will refuse, but **"Take a photo of the barcode"** and typing the barcode both work. For live scanning on the phone, put the app behind a TLS reverse proxy (Caddy, Traefik, nginx) or a tunnel.
## How the numbers work
Everything is an estimate, not lab-grade measurement.
| Piece | Formula |
| --- | --- |
| BMR | Mifflin-St Jeor: `10·kg + 6.25·cm − 5·age + 5` (male) / `−161` (female) |
| Daily living | `BMR × 1.2` (sedentary) |
| Steps | `steps × kg × 0.0005` (≈0.04 kcal/step at 80 kg) |
| Workout | `MET × 3.5 × kg ÷ 200 × minutes` |
| Intake target | `daily living + steps + workouts ± goal rate`, with a 1,200/1,500 kcal floor |
Goal rate uses 7,700 kcal per kg: losing 0.5 kg/week subtracts 550 kcal/day. The "You" tab shows every component and lets you override the protein target (default `1.6 g/kg`, or `1.8 g/kg` when losing). Apple Health workouts use the calories Apple measured; step calories are always estimated with the formula above.
Food values come from whichever product or portion you log. Unpackaged food you cook yourself has to be added manually.
## Apple Health
Browsers have no HealthKit access, so Counter gets Apple Health data three ways.
### Import an export (history)
1. iPhone: Health app → your profile → **Export All Health Data** → save and unzip it.
2. Open Counter → **You** → **Apple Health** → pick a date range and `export.xml`.
The file is parsed in the browser, so the multi-hundred-MB export never leaves the phone; only daily step totals and workout summaries are sent to the server. Steps are summed per day and workouts keep Apple's measured calories when present. Re-importing is safe: workouts are deduplicated by start time and each day's step total is replaced.
### Push from a shortcut (daily)
Set `INGEST_TOKEN` in `.env`, restart, then have an iOS Shortcut read Health and post it:
```bash
curl -X POST http://HOST:31490/api/ingest/health \
-H "Authorization: Bearer $INGEST_TOKEN" \
-H "Content-Type: application/json" \
-d '{"steps": 8500, "workouts": [{"name": "Running", "minutes": 32, "kcal": 310, "met": 9}]}'
```
`date` defaults to today (add `"date": "YYYY-MM-DD"` to backfill) and `workouts` is optional. `POST /api/ingest/steps` still works for a steps-only shortcut. Without `INGEST_TOKEN` both return 403.
### Automate with Health Auto Export (dynamic)
[Health Auto Export](https://www.healthautoexport.com/) is a commercial iOS app that reads HealthKit on the phone and POSTs JSON to an endpoint on a schedule. Counter understands its REST payload directly.
1. In Health Auto Export, create an automation with type **REST API**.
2. URL: `http://<server-ip>:31490/api/ingest/health-auto-export`.
3. Add header `Authorization` = `Bearer <INGEST_TOKEN>` (the token from `.env`).
4. Health metrics automation: select **Step Count**, turn **Summarize Data** on, group by **Days**, date range **Today** (or **Previous 7 Days** for a backfill), every 30–60 minutes.
5. Workouts automation: data type **Workouts**, **Export Version 2**, date range **Previous 7 Days**, daily.
6. Use **Manual Upload** once to backfill history.
Health Auto Export allows one data type per automation, which is why steps and workouts are separate. Each request replaces that day's step total and deduplicates workouts by the app's workout `id`, so repeats and retries are safe. iOS must be unlocked to read Health data and background runs can be delayed; the app's own docs call the frequency a desired cadence, not a guarantee.
If the phone cannot reach the server over plain HTTP, use HTTPS. `/api/ingest/health` remains available for anything that posts `{ "steps": …, "workouts": […] }`.
Either push path raises that day's burn, and therefore the calories you can eat, by the imported activity. You can also type steps on the Today tab; the target always reflects whatever arrived most recently.
## Bridges for steps and workouts
There is no Apple Health cloud REST API and no HealthKit access from a browser: the phone has to push the data. The practical options:
| Bridge | Runs on | Path into Counter | Notes |
| --- | --- | --- | --- |
| Apple Health export | iPhone | **You → Apple Health** picker | Built in. Manual, but complete history parsed on the phone. |
| Health Auto Export | iOS | `/api/ingest/health-auto-export` | Built in. Scheduled background push, separate automations for metrics and workouts. Commercial app. |
| iOS Shortcuts | iOS | `/api/ingest/health` | Free. Health actions inside Shortcuts, run from a personal automation; iOS decides when it fires. |
| HealthSave | iOS | its own `/api/apple/batch` contract | Background sync and API key; Pro unlock. Needs an adapter, not implemented. |
| Health Data Export & AI Analyzer | iOS | REST/webhook with Bearer or Basic auth | Auto-sync with a compact preset payload; needs a mapping adapter. |
| Life Dashboard Companion | iOS | webhook / MQTT / Home Assistant | Paid, MIT-licensed; useful if you already run Home Assistant. |
| HC Webhook | Android | Health Connect → custom webhook | One-time purchase, 31 data types including steps and exercise sessions; needs a payload mapper. |
| Terra, Spike, Junction, Sahha, Rook | cloud | hosted webhook | Connect Apple Health, Health Connect and wearables for you, but entry pricing is hundreds per month and requires OAuth/SDK setup. |
| Open Wearables | self-hosted | MIT aggregator | Self-hosted alternative to the SaaS aggregators. |
Android note: Health Connect has no web API, and the Google Fit REST API is deprecated in 2026 (no new signups since May 2024). On Android, use a Health Connect exporter such as HC Webhook, or post to `/api/ingest/health` from Tasker or Home Assistant.
## Configuration
| Variable | Default | Purpose |
| --- | --- | --- |
| `APP_PORT` | `31490` | Host port published by Compose (picks a high, unlikely-to-collide number) |
| `PORT` (deprecated) | — | Use `APP_PORT` instead |
| `TZ` | `UTC` | Used when a pushed step count has no date |
| `DATA_DIR` | `./data` (`/data` in Docker) | SQLite database and WAL files |
| `INGEST_TOKEN` | unset | Enables the ingest endpoints (`steps`, `health`, `health-auto-export`) |
| `OFF_BASE_URL` | `https://world.openfoodfacts.org` | Point at a mirror if needed |
| `OFF_TIMEOUT_MS` | `8000` | Open Food Facts request timeout |
The app has no login. It is built for a trusted home network — do not expose it to the internet without adding auth at the reverse proxy (and HTTPS, which also fixes the camera).
## Development
```bash
npm install
npm run dev # http://localhost:31490, restarts on file changes
npm test # energy, planner and nutrition unit tests
```
Layout:
```
server/
index.js HTTP routes (day, entries, activities, plan, food, ingest)
db.js SQLite schema and profile helpers
energy.js BMR, steps, MET and daily target maths
nutrition.js Open Food Facts client + 30-day barcode cache
planner.js Meal plan selection
health-auto-export.js Health Auto Export payload adapter
seed.js Built-in meal library, MET presets, diet styles
public/ Single-page mobile frontend (no build step)
test/ node:test unit tests
```
The barcode cache is stored in SQLite, so a repeat scan works even if Open Food Facts is briefly unreachable.
## Data sources
- Food and barcode data: Open Food Facts, available under the [Open Database License](https://opendatacommons.org/licenses/odbl/). Product data is crowd-sourced and can be incomplete or wrong.
- Meal library and MET values are included in `server/seed.js`; MET values follow the Compendium of Physical Activities.
## Limits
- No native step sensor or direct Apple Health / Google Fit sync: HealthKit and Health Connect are on-device APIs, so use the export import, Health Auto Export, or a Shortcut.
- Imported step records are summed across sources, so a phone and a watch can slightly over-count a day.
- No accounts or multi-user support.
- No photo/visual food recognition — scanning is barcode-based.
- Nutrition estimates are only as good as the logged product data.
+20
View File
@@ -0,0 +1,20 @@
services:
counter:
build: .
image: counter:latest
container_name: counter
restart: unless-stopped
ports:
- "${APP_PORT:-31490}:31490"
environment:
TZ: ${TZ:-UTC}
APP_PORT: "31490"
DATA_DIR: /data
# Optional: enables POST /api/ingest/steps for phone shortcuts.
INGEST_TOKEN: ${INGEST_TOKEN:-}
volumes:
- counter-data:/data
volumes:
counter-data:
name: counter-data
+897
View File
@@ -0,0 +1,897 @@
{
"name": "counter",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "counter",
"version": "1.0.0",
"dependencies": {
"@zxing/library": "^0.23.0",
"express": "^5.3.0"
},
"engines": {
"node": ">=22.13.0"
}
},
"node_modules/@zxing/library": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.23.0.tgz",
"integrity": "sha512-6fkkoFwP8CHxl6ugnPsj74PLJgX2iRv5zczGAyt5OBzQgxFhuhF0NCEc4t4OvSr8xAv2MRLlI0Iu9ZGDZQ2urA==",
"license": "Apache-2.0",
"dependencies": {
"ts-custom-error": "^3.3.1"
},
"engines": {
"node": ">= 24.0.0"
},
"optionalDependencies": {
"@zxing/text-encoding": "~0.9.0"
}
},
"node_modules/@zxing/text-encoding": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz",
"integrity": "sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==",
"license": "(Unlicense OR Apache-2.0)",
"optional": true
},
"node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
"integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
"license": "MIT",
"dependencies": {
"mime-types": "^3.0.0",
"negotiator": "^1.0.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/body-parser": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz",
"integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==",
"license": "MIT",
"dependencies": {
"bytes": "^3.1.2",
"content-type": "^2.1.0",
"debug": "^4.4.3",
"http-errors": "^2.0.1",
"iconv-lite": "^0.7.3",
"on-finished": "^2.4.1",
"qs": "^6.16.1",
"raw-body": "^3.0.2",
"type-is": "^2.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/bytes": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
"integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/call-bound": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
"integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"get-intrinsic": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/content-disposition": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz",
"integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/content-type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/cookie-signature": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
"integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
"license": "MIT",
"engines": {
"node": ">=6.6.0"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/depd": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
"integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/ee-first": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
"license": "MIT"
},
"node_modules/encodeurl": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz",
"integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
"integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escape-html": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
"integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
"license": "MIT"
},
"node_modules/etag": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
"integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/express": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz",
"integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==",
"license": "MIT",
"dependencies": {
"accepts": "^2.0.0",
"body-parser": "^2.3.0",
"content-disposition": "^2.0.1",
"content-type": "^2.0.0",
"cookie": "^0.7.1",
"cookie-signature": "^1.2.1",
"debug": "^4.4.0",
"depd": "^2.0.0",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"finalhandler": "^2.1.0",
"fresh": "^2.0.0",
"http-errors": "^2.0.0",
"merge-descriptors": "^2.0.0",
"mime-types": "^3.0.0",
"on-finished": "^2.4.1",
"once": "^1.4.0",
"parseurl": "^1.3.3",
"proxy-addr": "^2.0.8",
"qs": "^6.16.0",
"range-parser": "^1.2.1",
"router": "^2.2.0",
"send": "^1.1.0",
"serve-static": "^2.2.0",
"statuses": "^2.0.1",
"type-is": "^2.1.0",
"vary": "^1.1.2"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/finalhandler": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
"integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"on-finished": "^2.4.1",
"parseurl": "^1.3.3",
"statuses": "^2.0.1"
},
"engines": {
"node": ">= 18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
"integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/fresh": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
"integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
"integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
"integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
"license": "MIT",
"dependencies": {
"depd": "~2.0.0",
"inherits": "~2.0.4",
"setprototypeof": "~1.2.0",
"statuses": "~2.0.2",
"toidentifier": "~1.0.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/iconv-lite": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
},
"node_modules/ipaddr.js": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
"integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
"license": "MIT",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/is-promise": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/media-typer": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",
"integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/merge-descriptors": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
"integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/mime-db": {
"version": "1.54.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
"integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
"integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
"license": "MIT",
"dependencies": {
"mime-db": "^1.54.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/negotiator": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",
"integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",
"license": "MIT",
"dependencies": {
"content-type": "^2.1.0"
},
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/object-inspect": {
"version": "1.13.4",
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
"integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/on-finished": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz",
"integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==",
"license": "MIT",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
"integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/path-to-regexp": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
"integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/proxy-addr": {
"version": "2.0.8",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
"integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
"license": "MIT",
"dependencies": {
"forwarded": "0.2.0",
"ipaddr.js": "1.9.1"
},
"engines": {
"node": ">= 0.10"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/qs": {
"version": "6.17.1",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz",
"integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==",
"license": "BSD-3-Clause",
"dependencies": {
"es-define-property": "^1.0.1",
"side-channel": "^1.1.1"
},
"engines": {
"node": ">=0.6"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/range-parser": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
"integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/raw-body": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
"integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
"license": "MIT",
"dependencies": {
"bytes": "~3.1.2",
"http-errors": "~2.0.1",
"iconv-lite": "~0.7.0",
"unpipe": "~1.0.0"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/router": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
"integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.0",
"depd": "^2.0.0",
"is-promise": "^4.0.0",
"parseurl": "^1.3.3",
"path-to-regexp": "^8.0.0"
},
"engines": {
"node": ">= 18"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/send": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
"integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
"license": "MIT",
"dependencies": {
"debug": "^4.4.3",
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"etag": "^1.8.1",
"fresh": "^2.0.0",
"http-errors": "^2.0.1",
"mime-types": "^3.0.2",
"ms": "^2.1.3",
"on-finished": "^2.4.1",
"range-parser": "^1.2.1",
"statuses": "^2.0.2"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/serve-static": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
"integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
"license": "MIT",
"dependencies": {
"encodeurl": "^2.0.0",
"escape-html": "^1.0.3",
"parseurl": "^1.3.3",
"send": "^1.2.0"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
"node_modules/side-channel": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
"integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4",
"side-channel-list": "^1.0.1",
"side-channel-map": "^1.0.1",
"side-channel-weakmap": "^1.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-list": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
"integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"object-inspect": "^1.13.4"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-map": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
"integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/side-channel-weakmap": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
"integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
"license": "MIT",
"dependencies": {
"call-bound": "^1.0.2",
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.5",
"object-inspect": "^1.13.3",
"side-channel-map": "^1.0.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
"integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/toidentifier": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
"integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
"license": "MIT",
"engines": {
"node": ">=0.6"
}
},
"node_modules/ts-custom-error": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",
"integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/type-is": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
"integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
"license": "MIT",
"dependencies": {
"content-type": "^2.0.0",
"media-typer": "^1.1.0",
"mime-types": "^3.0.0"
},
"engines": {
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
"integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
"integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
"license": "MIT",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"name": "counter",
"version": "1.0.0",
"private": true,
"description": "Self-hosted calorie counter: scan food, track steps and workouts, plan meals.",
"main": "server/index.js",
"scripts": {
"start": "node server/index.js",
"dev": "node --watch server/index.js",
"test": "node --test test/*.test.js"
},
"engines": {
"node": ">=22.13.0"
},
"dependencies": {
"@zxing/library": "^0.23.0",
"express": "^5.3.0"
}
}
+867
View File
@@ -0,0 +1,867 @@
(() => {
'use strict';
const MEALS = [['breakfast', 'Breakfast'], ['lunch', 'Lunch'], ['dinner', 'Dinner'], ['snack', 'Snacks']];
const state = {
date: localDate(),
day: null,
meta: { metPresets: [], styles: [] },
view: 'today',
scanTab: 'scan',
product: null,
results: [],
meal: 'lunch',
controls: null,
busy: false,
};
const $ = (selector, root = document) => root.querySelector(selector);
const $$ = (selector, root = document) => Array.from(root.querySelectorAll(selector));
const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (ch) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
}[ch]));
const round = (n) => Math.round(Number(n) || 0);
const fmt = (n) => round(n).toLocaleString();
// ---------------------------------------------------------------- helpers
function localDate(date = new Date()) {
const shifted = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return shifted.toISOString().slice(0, 10);
}
function shiftDate(iso, days) {
const date = new Date(`${iso}T12:00:00`);
date.setDate(date.getDate() + days);
return localDate(date);
}
function prettyDate(iso) {
const today = localDate();
if (iso === today) return 'Today';
if (iso === shiftDate(today, -1)) return 'Yesterday';
if (iso === shiftDate(today, 1)) return 'Tomorrow';
return new Date(`${iso}T12:00:00`).toLocaleDateString(undefined, {
weekday: 'short', month: 'short', day: 'numeric',
});
}
function mealLabel(id) {
const match = MEALS.find((meal) => meal[0] === id);
return match ? match[1] : 'Snacks';
}
function mealOptions(selected) {
return MEALS.map(([id, label]) =>
`<option value="${id}"${id === selected ? ' selected' : ''}>${label}</option>`).join('');
}
let toastTimer = null;
function toast(message, kind = '') {
const el = $('#toast');
el.textContent = message;
el.className = `toast show ${kind}`.trim();
clearTimeout(toastTimer);
toastTimer = setTimeout(() => { el.className = 'toast'; }, 2800);
}
async function api(path, options = {}) {
const res = await fetch(`/api${path}`, {
...options,
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
});
let data = {};
try {
data = await res.json();
} catch {
/* non-JSON error */
}
if (!res.ok) throw new Error(data.error || `Request failed (${res.status})`);
return data;
}
const post = (path, body = {}) => api(path, { method: 'POST', body: JSON.stringify(body) });
const put = (path, body = {}) => api(path, { method: 'PUT', body: JSON.stringify(body) });
const del = (path) => api(path, { method: 'DELETE' });
// -------------------------------------------------------------- rendering
function renderToday() {
const view = $('#view-today');
if (!state.day) {
view.innerHTML = '<div class="card"><p class="muted">Loading…</p></div>';
return;
}
const day = state.day;
const totals = day.totals;
const targets = day.targets;
const remaining = targets.targetKcal - totals.kcal;
const over = remaining < 0;
const fraction = targets.targetKcal > 0
? Math.min(1, Math.max(0, totals.kcal / targets.targetKcal))
: 0;
const radius = 52;
const circumference = 2 * Math.PI * radius;
view.innerHTML = `
${day.profile.onboarded ? '' : '<button class="banner" type="button" data-action="open-profile">Set up your profile — targets are using placeholder numbers.</button>'}
<div class="card hero">
<div class="hero-ring">
<svg class="ring" viewBox="0 0 120 120" aria-hidden="true">
<circle class="ring-bg" cx="60" cy="60" r="${radius}"></circle>
<circle class="ring-fg${over ? ' over' : ''}" cx="60" cy="60" r="${radius}"
stroke-dasharray="${circumference.toFixed(1)}"
stroke-dashoffset="${(circumference * (1 - fraction)).toFixed(1)}"></circle>
</svg>
<div class="hero-center">
<span class="hero-num">${fmt(Math.abs(remaining))}</span>
<span class="hero-label">${over ? 'kcal over' : 'kcal left'}</span>
</div>
</div>
<div class="hero-stats">
<div><span class="muted">Eaten</span><strong>${fmt(totals.kcal)}</strong></div>
<div><span class="muted">Burned</span><strong>${fmt(targets.totalBurnKcal)}</strong></div>
<div><span class="muted">Target</span><strong>${fmt(targets.targetKcal)}</strong></div>
</div>
</div>
<div class="card">
${macroBar('Protein', totals.protein_g, targets.protein_g, 'protein')}
${macroBar('Carbs', totals.carbs_g, targets.carbs_g, 'carbs')}
${macroBar('Fat', totals.fat_g, targets.fat_g, 'fat')}
<p class="micro muted">Fiber ${round(totals.fiber_g)} g · Sugar ${round(totals.sugar_g)} g · Sodium ${fmt(totals.sodium_mg)} mg</p>
</div>
<div class="card">
<div class="row between"><h2>Movement</h2><span class="pill">${fmt(targets.stepKcal)} kcal from steps</span></div>
<div class="steps-row">
<form class="row-form" id="stepsForm" autocomplete="off">
<input name="steps" type="number" inputmode="numeric" min="0" max="200000"
value="${day.steps || ''}" placeholder="Steps today" aria-label="Steps today">
<button class="btn" type="submit">Save</button>
</form>
<div class="chips">
<button class="chip" type="button" data-action="steps-add" data-amount="1000">+1,000</button>
<button class="chip" type="button" data-action="steps-add" data-amount="2000">+2,000</button>
</div>
</div>
${exerciseList(day)}
<form class="row-form" id="exerciseForm" autocomplete="off">
<select name="preset" aria-label="Workout type">${metOptions()}</select>
<input name="minutes" type="number" inputmode="numeric" min="1" max="600" placeholder="min" aria-label="Minutes" required>
<button class="btn" type="submit">Add</button>
</form>
<p class="hint">Your burn estimate is your BMR-based baseline plus ${fmt(targets.stepKcal)} kcal of steps and ${fmt(targets.exerciseKcal)} kcal of workouts.</p>
</div>
<div class="meals">${mealSections(day)}</div>
`;
}
function macroBar(label, value, target, cls) {
const percent = target > 0 ? Math.min(100, (value / target) * 100) : 0;
return `<div class="macro ${cls}">
<div class="row between"><span>${label}</span><span class="muted">${round(value)} / ${round(target)} g</span></div>
<div class="track ${cls}"><span style="width:${percent.toFixed(1)}%"></span></div>
</div>`;
}
function mealSections(day) {
return MEALS.map(([id, label]) => {
const items = day.entries.filter((entry) => entry.meal === id);
const kcal = items.reduce((sum, entry) => sum + entry.kcal, 0);
return `<div class="card meal">
<div class="row between"><h2>${label}</h2><span class="pill">${fmt(kcal)} kcal</span></div>
${items.length
? `<ul class="entry-list">${items.map(entryRow).join('')}</ul>`
: '<p class="muted empty">Nothing logged yet.</p>'}
<button class="btn ghost small" type="button" data-action="goto-scan" data-meal="${id}">+ Add ${label.toLowerCase()}</button>
</div>`;
}).join('');
}
function entryRow(entry) {
return `<li class="entry">
<div class="entry-main">
<span class="entry-name">${esc(entry.name)}</span>
<span class="entry-meta">${entry.grams ? `${round(entry.grams)} g · ` : ''}${round(entry.protein_g)}P / ${round(entry.carbs_g)}C / ${round(entry.fat_g)}F</span>
</div>
<span class="entry-kcal">${fmt(entry.kcal)}</span>
<button class="x" type="button" data-action="del-entry" data-id="${entry.id}" aria-label="Remove ${esc(entry.name)}">×</button>
</li>`;
}
function exerciseList(day) {
const items = day.activities.filter((activity) => activity.type === 'exercise');
if (!items.length) return '';
return `<ul class="entry-list">${items.map((activity) => {
const origin = activity.source === 'apple_health'
? ' · Apple Health'
: activity.source === 'shortcut'
? ' · Shortcut'
: activity.source === 'health-auto-export' ? ' · Health Auto Export' : '';
return `<li class="entry">
<div class="entry-main">
<span class="entry-name">${esc(activity.name)}</span>
<span class="entry-meta">${round(activity.minutes)} min · MET ${activity.met}${origin}</span>
</div>
<span class="entry-kcal">${fmt(activity.kcal)}</span>
<button class="x" type="button" data-action="del-activity" data-id="${activity.id}" aria-label="Remove ${esc(activity.name)}">×</button>
</li>`;
}).join('')}</ul>`;
}
function metOptions() {
return (state.meta.metPresets || [])
.map((preset) => `<option value="${esc(preset.id)}">${esc(preset.label)}</option>`)
.join('');
}
function renderPlan() {
const list = $('#planList');
if (!list || !state.day) return;
const plan = state.day.plan;
const targets = state.day.targets;
$('#planTarget').textContent = `Target for ${prettyDate(state.date).toLowerCase()}: ${fmt(targets.targetKcal)} kcal and ${fmt(targets.protein_g)} g protein.`;
if (!plan) {
list.innerHTML = '<div class="card"><p class="muted" style="margin:0">No plan yet. Pick a style and generate a day of meals that fits your target.</p></div>';
return;
}
const totals = plan.totals;
list.innerHTML = `
<div class="card plan-summary">
<div class="row between"><h2>Your plan</h2><span class="pill">${fmt(totals.kcal)} kcal</span></div>
<p class="muted">${round(totals.protein_g)}P / ${round(totals.carbs_g)}C / ${round(totals.fat_g)}F · target ${fmt(targets.targetKcal)} kcal</p>
<button class="btn ghost small" type="button" data-action="clear-plan">Clear plan</button>
</div>
${plan.items.map(planCard).join('')}
<p class="hint">Ideas from the built-in meal library. Log one to add it to your day, or use the list as a shopping plan.</p>
`;
}
function planCard(item) {
return `<div class="card meal">
<div class="row between"><h3>${esc(item.name)}</h3><span class="pill">${fmt(item.kcal)} kcal</span></div>
<p class="muted small">${mealLabel(item.meal)} · ${round(item.protein_g)}P / ${round(item.carbs_g)}C / ${round(item.fat_g)}F${item.prep ? ` · ${item.prep} min` : ''}</p>
<p class="ingredients">${esc((item.ingredients || []).join(' · '))}</p>
<button class="btn small" type="button" data-action="log-plan" data-id="${item.id}">Log ${mealLabel(item.meal).toLowerCase()}</button>
</div>`;
}
function renderYouTargets() {
const card = $('#targetsCard');
if (!card || !state.day) return;
const targets = state.day.targets;
card.innerHTML = `
<div class="row between"><h2>Daily targets</h2><span class="pill">${fmt(targets.targetKcal)} kcal</span></div>
<dl class="stats">
<div><dt>BMR</dt><dd>${fmt(targets.bmrKcal)}</dd></div>
<div><dt>Daily living</dt><dd>${fmt(targets.basalKcal)}</dd></div>
<div><dt>Steps</dt><dd>${fmt(targets.stepKcal)}</dd></div>
<div><dt>Workouts</dt><dd>${fmt(targets.exerciseKcal)}</dd></div>
<div><dt>Goal change</dt><dd>${targets.adjustKcal > 0 ? '+' : ''}${fmt(targets.adjustKcal)}</dd></div>
<div><dt>Protein</dt><dd>${fmt(targets.protein_g)} g</dd></div>
</dl>
`;
}
function fillProfileForm() {
const form = $('#profileForm');
const profile = state.day && state.day.profile;
if (!form || !profile) return;
form.name.value = profile.name || '';
form.sex.value = profile.sex === 'female' ? 'female' : 'male';
form.age.value = profile.age;
form.height_cm.value = profile.height_cm;
form.weight_kg.value = profile.weight_kg;
form.goal.value = profile.goal;
form.rate_kg_week.value = profile.rate_kg_week;
form.diet.value = profile.diet;
form.protein_target_g.value = profile.protein_target_g ?? '';
}
function renderProduct(product) {
const box = $('#scanResult');
if (!box) return;
if (!product) {
box.innerHTML = '';
return;
}
const per = product.per100g;
const grams = product.servingGrams || 100;
const kcal = Math.round((per.kcal * grams) / 100);
box.innerHTML = `<div class="card product">
<div class="product-head">
${product.image ? `<img class="product-img" src="${esc(product.image)}" alt="" loading="lazy">` : ''}
<div>
<h3>${esc(product.name)}</h3>
<p class="muted small" style="margin:0">${esc(product.brand || product.source || 'Open Food Facts')}${product.servingLabel ? ` · serving ${esc(product.servingLabel)}` : ''}</p>
<p class="small" style="margin:6px 0 0">${per.kcal} kcal · ${per.protein_g}P / ${per.carbs_g}C / ${per.fat_g}F per 100 g</p>
</div>
</div>
<form id="logProductForm" autocomplete="off">
<div class="row-form">
<input name="grams" type="number" inputmode="decimal" min="1" max="5000" step="1" value="${grams}" aria-label="Portion in grams" required>
<span class="unit">grams</span>
<span class="product-kcal" id="productKcal">${kcal} kcal</span>
</div>
<div class="chips">
${product.servingGrams ? `<button class="chip" type="button" data-action="portion" data-grams="${product.servingGrams}">Serving (${round(product.servingGrams)} g)</button>` : ''}
<button class="chip" type="button" data-action="portion" data-grams="100">100 g</button>
</div>
<div class="row-form">
<select name="meal" aria-label="Meal">${mealOptions(state.meal)}</select>
<button class="btn primary" type="submit">Add to day</button>
</div>
</form>
</div>`;
}
function updateProductKcal() {
const product = state.product;
const form = $('#logProductForm');
const out = $('#productKcal');
if (!product || !form || !out) return;
const grams = Number(form.querySelector('[name="grams"]').value) || 0;
out.textContent = `${fmt((product.per100g.kcal * grams) / 100)} kcal`;
}
// ------------------------------------------------------------------- data
async function loadDay() {
const day = await api(`/day/${state.date}`);
state.day = day;
$('#dateLabel').textContent = prettyDate(state.date);
const next = $('[data-action="date-next"]');
if (next) next.disabled = state.date >= localDate();
renderToday();
renderPlan();
renderYouTargets();
if (state.view === 'you') fillProfileForm();
if (state.product) renderProduct(state.product);
}
function finishLogging(day, meal) {
state.day = day;
state.product = null;
renderProduct(null);
renderToday();
renderPlan();
renderYouTargets();
setView('today');
toast(`Added to ${mealLabel(meal).toLowerCase()}`);
}
// ------------------------------------------------------------------- scan
function setScanTab(tab) {
state.scanTab = tab;
$$('[data-scan-tab]').forEach((button) => {
button.classList.toggle('is-active', button.dataset.scanTab === tab);
button.setAttribute('aria-selected', button.dataset.scanTab === tab ? 'true' : 'false');
});
['scan', 'search', 'manual'].forEach((name) => {
const pane = $(`#scanPane-${name}`);
if (pane) pane.hidden = name !== tab;
});
if (tab !== 'scan') stopCamera();
}
async function lookupBarcode(code) {
const box = $('#scanResult');
box.innerHTML = '<div class="card"><p class="muted" style="margin:0">Looking up barcode…</p></div>';
try {
const data = await api(`/foods/barcode/${encodeURIComponent(code)}`);
state.product = data.product;
renderProduct(state.product);
if (navigator.vibrate) navigator.vibrate(50);
} catch (err) {
state.product = null;
box.innerHTML = `<div class="card">
<h3>No match</h3>
<p class="muted">${esc(err.message)}</p>
<p class="hint">Barcode ${esc(code)}</p>
<button class="btn ghost small" type="button" data-action="goto-manual">Add it manually</button>
</div>`;
}
}
async function runSearch(query) {
const box = $('#searchResults');
box.innerHTML = '<p class="muted pad">Searching Open Food Facts…</p>';
const data = await api(`/foods/search?q=${encodeURIComponent(query)}`);
state.results = data.products || [];
if (!state.results.length) {
box.innerHTML = `<div class="card">
<p class="muted" style="margin:0 0 10px">No matches for “${esc(query)}”. Try a shorter name, or add it manually.</p>
<button class="btn ghost small" type="button" data-action="goto-manual">Add manually</button>
</div>`;
return;
}
box.innerHTML = state.results.map((product, index) => `<button class="result" type="button" data-action="pick-product" data-index="${index}">
${product.image
? `<img src="${esc(product.image)}" alt="" loading="lazy">`
: '<span class="result-placeholder"></span>'}
<span class="result-main">
<strong>${esc(product.name)}</strong>
<span class="muted small">${esc(product.brand || '')} · ${product.per100g.kcal} kcal/100 g</span>
</span>
</button>`).join('');
}
async function startCamera() {
if (!window.isSecureContext) {
toast('Camera needs HTTPS — take a photo or type the barcode instead', 'error');
return;
}
if (!window.ZXing) {
toast('Scanner library did not load', 'error');
return;
}
const button = $('#startCameraBtn');
const box = $('#cameraBox');
const video = $('#camera');
button.disabled = true;
box.hidden = false;
try {
const reader = new ZXing.BrowserMultiFormatReader();
state.controls = await reader.decodeFromConstraints(
{ audio: false, video: { facingMode: { ideal: 'environment' } } },
video,
(result) => {
if (!result) return;
const code = result.getText();
stopCamera();
lookupBarcode(code);
}
);
$('#cameraHint').textContent = 'Hold the barcode inside the frame.';
} catch (err) {
box.hidden = true;
button.disabled = false;
$('#cameraHint').textContent = `Camera unavailable: ${err && err.message ? err.message : 'permission denied'}. Try a photo instead.`;
}
}
function stopCamera() {
if (state.controls) {
try { state.controls.stop(); } catch { /* already stopped */ }
state.controls = null;
}
const box = $('#cameraBox');
if (box) box.hidden = true;
const button = $('#startCameraBtn');
if (button) button.disabled = false;
}
async function onPhoto(event) {
const file = event.target.files && event.target.files[0];
event.target.value = '';
if (!file) return;
if (!window.ZXing) {
toast('Scanner library did not load', 'error');
return;
}
const url = URL.createObjectURL(file);
try {
const reader = new ZXing.BrowserMultiFormatReader();
const result = await reader.decodeFromImageUrl(url);
await lookupBarcode(result.getText());
} catch {
toast('No barcode found in that photo — try again closer', 'error');
} finally {
URL.revokeObjectURL(url);
}
}
async function onHealthFile(event) {
const file = event.target.files && event.target.files[0];
event.target.value = '';
if (!file) return;
const status = $('#importStatus');
const setStatus = (message) => { if (status) status.textContent = message; };
if (!window.HealthImport) {
toast('Import script did not load', 'error');
return;
}
const daysBack = Number($('#importRange').value) || 90;
const since = shiftDate(localDate(), -daysBack);
setStatus('Reading export…');
try {
const parsed = await window.HealthImport.parseFile(file, {
since,
onProgress: (fraction) => setStatus(`Reading export… ${Math.round(fraction * 100)}%`),
});
if (!parsed.days.length && !parsed.workouts.length) {
setStatus(`No steps or workouts found in the last ${daysBack} days.`);
return;
}
setStatus(`Found ${parsed.days.length} step days and ${parsed.workouts.length} workouts. Saving…`);
const result = await post('/import/apple-health', parsed);
setStatus(`Imported ${result.stepsDays} step days and ${result.workouts} new workouts.`);
toast('Apple Health imported');
await loadDay();
} catch (err) {
setStatus(err.message);
toast(err.message, 'error');
}
}
// ------------------------------------------------------------------- view
function setView(view) {
if (view !== 'scan') stopCamera();
state.view = view;
$$('.view').forEach((section) => {
section.hidden = section.id !== `view-${view}`;
});
$$('.tab').forEach((tab) => {
tab.classList.toggle('is-active', tab.dataset.view === view);
});
if (view === 'plan') {
renderPlan();
const select = $('#planStyle');
const profile = state.day && state.day.profile;
if (select && profile && !select.value) select.value = profile.diet || 'any';
}
if (view === 'you') {
fillProfileForm();
renderYouTargets();
}
window.scrollTo(0, 0);
}
// ----------------------------------------------------------------- events
async function onClick(event) {
const tab = event.target.closest('.tab');
if (tab) {
setView(tab.dataset.view);
return;
}
const scanTab = event.target.closest('[data-scan-tab]');
if (scanTab) {
setScanTab(scanTab.dataset.scanTab);
return;
}
const el = event.target.closest('[data-action]');
if (!el) return;
try {
switch (el.dataset.action) {
case 'date-prev':
state.date = shiftDate(state.date, -1);
await loadDay();
break;
case 'date-next':
if (state.date >= localDate()) return;
state.date = shiftDate(state.date, 1);
await loadDay();
break;
case 'date-today':
state.date = localDate();
await loadDay();
break;
case 'open-profile':
setView('you');
break;
case 'goto-scan': {
state.meal = el.dataset.meal || 'lunch';
state.product = null;
renderProduct(null);
const manualMeal = $('#manualMeal');
if (manualMeal) manualMeal.value = state.meal;
setScanTab('scan');
setView('scan');
break;
}
case 'goto-manual':
setScanTab('manual');
break;
case 'del-entry': {
const data = await del(`/entries/${el.dataset.id}`);
state.day = data.day;
renderToday();
renderPlan();
renderYouTargets();
toast('Removed');
break;
}
case 'del-activity': {
const data = await del(`/activities/${el.dataset.id}`);
state.day = data.day;
renderToday();
renderYouTargets();
toast('Removed');
break;
}
case 'steps-add': {
const steps = (state.day && state.day.steps ? state.day.steps : 0) + Number(el.dataset.amount);
const data = await post('/activities', { date: state.date, type: 'steps', steps });
state.day = data.day;
renderToday();
renderYouTargets();
break;
}
case 'pick-product': {
const product = state.results[Number(el.dataset.index)];
if (!product) return;
state.product = product;
setScanTab('scan');
renderProduct(product);
break;
}
case 'portion': {
const form = $('#logProductForm');
const input = form && form.querySelector('[name="grams"]');
if (input) {
input.value = el.dataset.grams;
updateProductKcal();
}
break;
}
case 'log-plan': {
const data = await post(`/plan/items/${el.dataset.id}/log`, {});
state.day = data.day;
renderToday();
renderPlan();
renderYouTargets();
toast('Meal logged');
break;
}
case 'clear-plan': {
const data = await del(`/plan/${state.date}`);
state.day = data.day;
renderPlan();
toast('Plan cleared');
break;
}
case 'stop-camera':
stopCamera();
break;
case 'photo-scan':
$('#photoInput').click();
break;
default:
break;
}
} catch (err) {
toast(err.message, 'error');
}
}
async function onInput(event) {
if (event.target.closest('#logProductForm input[name="grams"]')) updateProductKcal();
}
async function onSubmit(event) {
const form = event.target;
if (!['stepsForm', 'exerciseForm', 'barcodeForm', 'searchForm', 'manualForm', 'logProductForm', 'profileForm'].includes(form.id)) return;
event.preventDefault();
if (state.busy) return;
try {
if (form.id === 'stepsForm') {
const steps = Math.max(0, Math.round(Number(form.steps.value) || 0));
const data = await post('/activities', { date: state.date, type: 'steps', steps });
state.day = data.day;
renderToday();
renderYouTargets();
toast('Steps saved');
return;
}
if (form.id === 'exerciseForm') {
const preset = (state.meta.metPresets || []).find((item) => item.id === form.preset.value);
const minutes = Number(form.minutes.value);
if (!preset) throw new Error('Pick an activity');
if (!(minutes > 0)) throw new Error('Enter the minutes');
const data = await post('/activities', {
date: state.date, type: 'exercise', name: preset.label, met: preset.met, minutes,
});
state.day = data.day;
renderToday();
renderYouTargets();
toast('Workout added');
return;
}
if (form.id === 'barcodeForm') {
const code = form.barcode.value.replace(/\D/g, '');
if (code.length < 6) throw new Error('Enter the digits under the barcode');
await lookupBarcode(code);
return;
}
if (form.id === 'searchForm') {
const query = form.q.value.trim();
if (query.length < 2) throw new Error('Search needs at least 2 characters');
await runSearch(query);
return;
}
if (form.id === 'manualForm') {
const body = {
date: state.date,
meal: form.meal.value,
name: form.name.value.trim(),
kcal: Number(form.kcal.value) || 0,
protein_g: Number(form.protein_g.value) || 0,
carbs_g: Number(form.carbs_g.value) || 0,
fat_g: Number(form.fat_g.value) || 0,
};
if (!body.name) throw new Error('Give the food a name');
if (!(body.kcal > 0)) throw new Error('Enter the calories');
const data = await post('/entries', body);
form.reset();
const mealSelect = $('#manualMeal');
if (mealSelect) mealSelect.value = body.meal;
finishLogging(data.day, body.meal);
return;
}
if (form.id === 'logProductForm') {
const product = state.product;
if (!product) throw new Error('Pick a product first');
const grams = Number(form.grams.value);
if (!(grams > 0)) throw new Error('Enter a portion in grams');
const meal = form.meal.value;
const data = await post('/entries', {
date: state.date,
meal,
name: product.name,
brand: product.brand,
barcode: product.code,
image_url: product.image,
grams,
per100g: product.per100g,
});
finishLogging(data.day, meal);
return;
}
if (form.id === 'profileForm') {
const body = {
name: form.name.value,
sex: form.sex.value,
age: Number(form.age.value),
height_cm: Number(form.height_cm.value),
weight_kg: Number(form.weight_kg.value),
goal: form.goal.value,
rate_kg_week: Number(form.rate_kg_week.value) || 0,
diet: form.diet.value,
protein_target_g: form.protein_target_g.value === '' ? null : Number(form.protein_target_g.value),
};
const data = await put('/profile', body);
state.day.profile = data.profile;
await loadDay();
toast('Profile saved');
}
} catch (err) {
toast(err.message, 'error');
}
}
async function generatePlan() {
const button = $('#generatePlanBtn');
if (state.busy) return;
state.busy = true;
button.disabled = true;
button.textContent = 'Planning…';
try {
const style = $('#planStyle').value || 'any';
const data = await post(`/plan/${state.date}`, { style });
state.day.plan = data.plan;
renderPlan();
toast('Plan ready');
} catch (err) {
toast(err.message, 'error');
} finally {
state.busy = false;
button.disabled = false;
button.textContent = 'Generate plan';
}
}
// ------------------------------------------------------------------- init
function fillMetaOptions() {
const styles = state.meta.styles || [];
const styleOptions = styles.map((style) => `<option value="${esc(style.id)}">${esc(style.label)}</option>`).join('');
const planStyle = $('#planStyle');
if (planStyle) planStyle.innerHTML = styleOptions;
const profileDiet = $('#profileDiet');
if (profileDiet) profileDiet.innerHTML = styleOptions;
const manualMeal = $('#manualMeal');
if (manualMeal) manualMeal.innerHTML = mealOptions(state.meal);
}
function bind() {
document.addEventListener('click', onClick);
document.addEventListener('submit', onSubmit);
document.addEventListener('input', onInput);
$('#photoInput').addEventListener('change', onPhoto);
const healthFile = $('#healthFile');
if (healthFile) healthFile.addEventListener('change', onHealthFile);
$('#startCameraBtn').addEventListener('click', startCamera);
$('#generatePlanBtn').addEventListener('click', generatePlan);
}
async function init() {
bind();
try {
state.meta = await api('/meta');
} catch (err) {
console.warn('Meta unavailable', err);
}
fillMetaOptions();
try {
await loadDay();
} catch (err) {
$('#view-today').innerHTML = `<div class="card"><h2>Can't load your day</h2><p class="error">${esc(err.message)}</p></div>`;
return;
}
setView('today');
const hint = $('#cameraHint');
if (!window.isSecureContext) {
hint.textContent = 'Live camera needs HTTPS or localhost. Taking a photo or typing the barcode works over plain HTTP.';
} else {
hint.textContent = 'Point the camera at the barcode. If it will not start, take a photo instead.';
}
}
init();
})();
+165
View File
@@ -0,0 +1,165 @@
/**
* Apple Health export parser.
*
* Reads `export.xml` in chunks so a several-hundred-megabyte export can be
* processed without leaving the phone or loading the whole file into memory.
* Only step records and workouts are kept.
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) module.exports = factory();
else root.HealthImport = factory();
}(typeof self !== 'undefined' ? self : this, function () {
'use strict';
const STEP_TYPE = 'HKQuantityTypeIdentifierStepCount';
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 },
CardioDance: { name: 'Dance', met: 5.5 },
HighIntensityIntervalTraining: { name: 'HIIT', met: 8.0 },
FunctionalStrengthTraining: { name: 'Strength training', met: 5.0 },
TraditionalStrengthTraining: { name: 'Strength training', met: 5.0 },
CoreTraining: { name: 'Core training', met: 3.5 },
Flexibility: { name: 'Stretching', met: 2.3 },
MindAndBody: { name: 'Yoga', met: 2.5 },
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 },
StairClimbing: { name: 'Stair climbing', met: 8.8 },
JumpRope: { name: 'Jump rope', met: 12.3 },
Boxing: { name: 'Boxing', met: 7.8 },
MartialArts: { name: 'Martial arts', met: 10.3 },
TeamSports: { name: 'Team sport', met: 7.0 },
Other: { name: 'Workout', met: 6.0 },
};
function parseAttrs(source) {
const attrs = {};
const re = /([A-Za-z_:][-A-Za-z0-9_:.]*)="([^"]*)"/g;
let match;
while ((match = re.exec(source))) attrs[match[1]] = match[2];
return attrs;
}
function localDay(value) {
if (typeof value !== 'string') return null;
const match = /^(\d{4}-\d{2}-\d{2})/.exec(value);
return match ? match[1] : null;
}
function appleDate(value) {
if (typeof value !== 'string') return NaN;
// Apple uses "2026-11-06 07:12:00 -0700".
const iso = value.trim().replace(' ', 'T').replace(/ ([+-]\d{2})(\d{2})$/, '$1:$2');
return Date.parse(iso);
}
function workoutMeta(type) {
const key = String(type || '').replace(/^HKWorkoutActivityType/, '');
if (WORKOUT_TYPES[key]) return WORKOUT_TYPES[key];
const name = key ? key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase() : 'workout';
return { name: name.charAt(0).toUpperCase() + name.slice(1), met: 6 };
}
function durationMinutes(attrs) {
const duration = Number(attrs.duration);
if (Number.isFinite(duration) && duration > 0) return duration;
const start = appleDate(attrs.startDate);
const end = appleDate(attrs.endDate);
if (Number.isFinite(start) && Number.isFinite(end) && end > start) {
return (end - start) / 60000;
}
return 0;
}
function createParser({ since = '' } = {}) {
let tail = '';
const stepDays = new Map();
const workouts = new Map();
function consume(text) {
const re = /<(Record|Workout)\b([^>]*)>/g;
let match;
while ((match = re.exec(text))) {
const attrs = parseAttrs(match[2]);
const day = localDay(attrs.startDate);
if (!day || (since && day < since)) continue;
if (match[1] === 'Record') {
if (attrs.type !== STEP_TYPE) continue;
const value = Number(attrs.value);
if (!Number.isFinite(value) || value <= 0) continue;
stepDays.set(day, (stepDays.get(day) || 0) + value);
continue;
}
const meta = workoutMeta(attrs.workoutActivityType);
const minutes = durationMinutes(attrs);
if (!(minutes > 0)) continue;
const externalId = `apple:${attrs.workoutActivityType || 'workout'}:${attrs.startDate}`;
if (workouts.has(externalId)) continue;
const energy = Number(attrs.totalEnergyBurned);
workouts.set(externalId, {
externalId,
date: day,
name: meta.name,
minutes: Math.round(minutes * 10) / 10,
kcal: Number.isFinite(energy) && energy > 0 ? Math.round(energy) : 0,
met: meta.met,
});
}
const lastOpen = text.lastIndexOf('<');
return lastOpen !== -1 && text.indexOf('>', lastOpen) === -1 ? text.slice(lastOpen) : '';
}
return {
push(text) {
tail = consume(tail + text);
},
finish() {
return {
days: Array.from(stepDays, ([date, steps]) => ({ date, steps: Math.round(steps) })),
workouts: Array.from(workouts.values()),
};
},
};
}
async function parseFile(file, options = {}) {
const parser = createParser(options);
const size = file.size || 0;
const chunkSize = 4 * 1024 * 1024;
let offset = 0;
while (offset < size) {
const text = await file.slice(offset, offset + chunkSize).text();
parser.push(text);
offset += chunkSize;
if (options.onProgress) {
options.onProgress(Math.min(1, offset / size));
}
}
if (options.onProgress) options.onProgress(1);
return parser.finish();
}
return { createParser, parseFile, STEP_TYPE, WORKOUT_TYPES };
}));
+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#0b0f14"/>
<circle cx="256" cy="256" r="150" fill="none" stroke="#5ddb92" stroke-width="40"
stroke-linecap="round" stroke-dasharray="700 242" transform="rotate(-90 256 256)"/>
<circle cx="256" cy="256" r="18" fill="#e6edf3"/>
</svg>

After

Width:  |  Height:  |  Size: 358 B

+184
View File
@@ -0,0 +1,184 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#0b0f14">
<meta name="description" content="Counter — scan food, track calories, steps and workouts, and get meal plans.">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Counter">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Counter</title>
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/icon.svg">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<header class="topbar">
<div class="brand">
<svg class="brand-mark" viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2.4"
stroke-dasharray="42 15" stroke-linecap="round" transform="rotate(-90 12 12)"/>
</svg>
<span>Counter</span>
</div>
<div class="date-nav">
<button class="icon-btn" type="button" data-action="date-prev" aria-label="Previous day">&#8249;</button>
<button class="date-label" type="button" id="dateLabel" data-action="date-today" title="Jump to today">Today</button>
<button class="icon-btn" type="button" data-action="date-next" aria-label="Next day">&#8250;</button>
</div>
</header>
<main>
<section class="view" id="view-today"></section>
<section class="view" id="view-scan" hidden>
<div class="view-head">
<h1>Scan food</h1>
<p class="muted">Barcode or name lookup, powered by Open Food Facts.</p>
</div>
<div class="segmented" role="tablist" aria-label="Food entry method">
<button type="button" data-scan-tab="scan" class="is-active" role="tab">Scan</button>
<button type="button" data-scan-tab="search" role="tab">Search</button>
<button type="button" data-scan-tab="manual" role="tab">Manual</button>
</div>
<div class="scan-pane" id="scanPane-scan">
<div class="card">
<div class="camera-box" id="cameraBox" hidden>
<video id="camera" playsinline muted></video>
<button class="btn ghost small" type="button" data-action="stop-camera">Stop camera</button>
</div>
<button class="btn primary block" type="button" id="startCameraBtn">Start camera</button>
<p class="hint" id="cameraHint">Point the camera at a barcode.</p>
<div class="or"><span>or</span></div>
<button class="btn block" type="button" data-action="photo-scan">Take a photo of the barcode</button>
<input type="file" id="photoInput" accept="image/*" capture="environment" hidden>
<form class="row-form" id="barcodeForm" autocomplete="off">
<input name="barcode" inputmode="numeric" pattern="[0-9]*" placeholder="Type the barcode digits" aria-label="Barcode digits">
<button class="btn" type="submit">Look up</button>
</form>
</div>
<div id="scanResult"></div>
</div>
<div class="scan-pane" id="scanPane-search" hidden>
<form class="row-form" id="searchForm" autocomplete="off">
<input name="q" placeholder="e.g. greek yogurt, oat milk" aria-label="Search foods">
<button class="btn" type="submit">Search</button>
</form>
<div id="searchResults"></div>
</div>
<div class="scan-pane" id="scanPane-manual" hidden>
<form class="card form-grid" id="manualForm" autocomplete="off">
<label class="field span-2"><span>Food name</span><input name="name" maxlength="120" placeholder="Homemade chili" required></label>
<label class="field"><span>Calories</span><input name="kcal" type="number" inputmode="numeric" min="0" max="5000" required></label>
<label class="field"><span>Protein (g)</span><input name="protein_g" type="number" inputmode="decimal" min="0" max="500" step="0.1" value="0"></label>
<label class="field"><span>Carbs (g)</span><input name="carbs_g" type="number" inputmode="decimal" min="0" max="500" step="0.1" value="0"></label>
<label class="field"><span>Fat (g)</span><input name="fat_g" type="number" inputmode="decimal" min="0" max="500" step="0.1" value="0"></label>
<label class="field span-2"><span>Meal</span><select name="meal" id="manualMeal"></select></label>
<button class="btn primary span-2" type="submit">Add to day</button>
</form>
</div>
</section>
<section class="view" id="view-plan" hidden>
<div class="view-head">
<h1>Meal plan</h1>
<p class="muted">Suggestions that fit what is left of your day.</p>
</div>
<div class="card">
<label class="field"><span>Style</span><select id="planStyle"></select></label>
<p class="hint" id="planTarget"></p>
<button class="btn primary block" type="button" id="generatePlanBtn">Generate plan</button>
</div>
<div id="planList"></div>
</section>
<section class="view" id="view-you" hidden>
<div class="view-head">
<h1>You</h1>
<p class="muted">Targets are estimates built from this profile.</p>
</div>
<form class="card form-grid" id="profileForm" autocomplete="off">
<label class="field span-2"><span>Name</span><input name="name" maxlength="60" placeholder="Your name"></label>
<label class="field"><span>Sex</span>
<select name="sex"><option value="male">Male</option><option value="female">Female</option></select>
</label>
<label class="field"><span>Age</span><input name="age" type="number" inputmode="numeric" min="13" max="120" required></label>
<label class="field"><span>Height (cm)</span><input name="height_cm" type="number" inputmode="decimal" min="100" max="250" step="0.1" required></label>
<label class="field"><span>Weight (kg)</span><input name="weight_kg" type="number" inputmode="decimal" min="30" max="300" step="0.1" required></label>
<label class="field"><span>Goal</span>
<select name="goal">
<option value="lose">Lose weight</option>
<option value="maintain">Maintain</option>
<option value="gain">Gain weight</option>
</select>
</label>
<label class="field"><span>Rate (kg/week)</span><input name="rate_kg_week" type="number" inputmode="decimal" min="0" max="1.5" step="0.1"></label>
<label class="field"><span>Meal style</span><select name="diet" id="profileDiet"></select></label>
<label class="field"><span>Protein target (g)</span><input name="protein_target_g" type="number" inputmode="numeric" min="0" max="400" placeholder="Auto"></label>
<button class="btn primary span-2" type="submit">Save profile</button>
</form>
<div class="card" id="targetsCard"></div>
<div class="card small-print">
<h2>Apple Health</h2>
<p class="muted">In the Health app open your profile → <strong>Export All Health Data</strong>, unzip it, then choose <code>export.xml</code> here. The file is read on this device; only daily step totals and workouts are sent to your server.</p>
<label class="field" style="margin-top:10px"><span>Date range</span>
<select id="importRange">
<option value="30">Last 30 days</option>
<option value="90" selected>Last 90 days</option>
<option value="365">Last year</option>
<option value="3650">Everything</option>
</select>
</label>
<label class="field" style="margin-top:10px"><span>Health export</span>
<input type="file" id="healthFile" accept=".xml,text/xml,application/xml">
</label>
<p class="hint" id="importStatus"></p>
</div>
<div class="card small-print">
<h2>Step data</h2>
<p class="muted">A browser cannot read the phone's step sensor. Log steps on the Today tab, or push them from a shortcut (iOS Shortcuts, Tasker) when <code>INGEST_TOKEN</code> is set on the server:</p>
<pre><code>curl -X POST http://HOST:31490/api/ingest/steps \
-H "Authorization: Bearer $INGEST_TOKEN" \
-H "Content-Type: application/json" \
-d '{"steps": 8500}'</code></pre>
<p class="muted small">Add <code>"date": "YYYY-MM-DD"</code> to backfill an earlier day. For scheduled Apple Health sync, point <strong>Health Auto Export</strong> at <code>/api/ingest/health-auto-export</code> with the same token; the README has the two-automation setup. Food data from Open Food Facts (ODbL).</p>
</div>
</section>
</main>
<nav class="tabbar" aria-label="Sections">
<button class="tab is-active" type="button" data-view="today">
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M8.5 12.2l2.4 2.4 4.6-5"/></svg>
<span>Today</span>
</button>
<button class="tab" type="button" data-view="scan">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 8V5.5A1.5 1.5 0 015.5 4H8M16 4h2.5A1.5 1.5 0 0120 5.5V8M20 16v2.5a1.5 1.5 0 01-1.5 1.5H16M8 20H5.5A1.5 1.5 0 014 18.5V16"/><path d="M7 12h10"/></svg>
<span>Scan</span>
</button>
<button class="tab" type="button" data-view="plan">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 7h14M5 12h14M5 17h9"/></svg>
<span>Plan</span>
</button>
<button class="tab" type="button" data-view="you">
<svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="8.5" r="3.5"/><path d="M5.5 20c.8-3.6 3.3-5.5 6.5-5.5s5.7 1.9 6.5 5.5"/></svg>
<span>You</span>
</button>
</nav>
<div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="/vendor/zxing/index.min.js"></script>
<script src="/health.js"></script>
<script src="/app.js"></script>
</body>
</html>
+18
View File
@@ -0,0 +1,18 @@
{
"name": "Counter",
"short_name": "Counter",
"description": "Scan food, track calories, steps and workouts, and get meal plans.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#0b0f14",
"theme_color": "#0b0f14",
"icons": [
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
}
]
}
+833
View File
@@ -0,0 +1,833 @@
*,
*::before,
*::after {
box-sizing: border-box;
}
:root {
color-scheme: dark;
--bg: #0b0f14;
--card: #121a23;
--card-top: #152029;
--line: #22303c;
--text: #e6edf3;
--muted: #8b98a5;
--accent: #5ddb92;
--accent-strong: #33a974;
--blue: #6cb6ff;
--warn: #f0a35e;
--danger: #ff7b72;
--radius: 18px;
}
html,
body {
margin: 0;
}
body {
min-height: 100dvh;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Inter, system-ui, sans-serif;
color: var(--text);
background:
radial-gradient(1100px 520px at 50% -10%, #16212b 0%, rgba(11, 15, 20, 0) 60%) no-repeat,
var(--bg);
-webkit-tap-highlight-color: transparent;
-webkit-font-smoothing: antialiased;
}
[hidden] {
display: none !important;
}
h1,
h2,
h3,
p {
margin-top: 0;
}
h2 {
margin-bottom: 0;
font-size: 14px;
letter-spacing: 0.02em;
color: #cbd5e1;
}
h3 {
margin-bottom: 4px;
font-size: 16px;
}
.topbar {
position: sticky;
top: 0;
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: calc(10px + env(safe-area-inset-top, 0px)) 16px 10px;
background: rgba(11, 15, 20, 0.86);
backdrop-filter: blur(16px);
border-bottom: 1px solid var(--line);
}
.brand {
display: flex;
align-items: center;
gap: 8px;
font-weight: 700;
letter-spacing: -0.01em;
}
.brand-mark {
width: 22px;
height: 22px;
color: var(--accent);
}
.date-nav {
display: flex;
align-items: center;
gap: 6px;
}
.icon-btn {
display: grid;
place-items: center;
width: 32px;
height: 32px;
padding: 0;
font-size: 18px;
line-height: 1;
color: var(--text);
background: #121a22;
border: 1px solid var(--line);
border-radius: 10px;
cursor: pointer;
}
.icon-btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.date-label {
min-width: 108px;
padding: 6px 4px;
font-size: 14px;
font-weight: 600;
color: var(--text);
background: none;
border: 0;
cursor: pointer;
}
main {
max-width: 560px;
margin: 0 auto;
padding: 16px 16px calc(92px + env(safe-area-inset-bottom, 0px));
}
.view {
display: grid;
gap: 14px;
}
.view-head h1 {
margin-bottom: 6px;
font-size: 24px;
letter-spacing: -0.02em;
}
.view-head p {
margin-bottom: 2px;
}
.card {
padding: 16px;
background: linear-gradient(180deg, var(--card-top), var(--card));
border: 1px solid var(--line);
border-radius: var(--radius);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
}
.muted {
color: var(--muted);
}
.small {
font-size: 13px;
}
.hint {
margin: 10px 0 0;
font-size: 12.5px;
line-height: 1.5;
color: #75828f;
}
.error {
color: var(--danger);
}
.row {
display: flex;
align-items: center;
gap: 10px;
}
.between {
justify-content: space-between;
}
.pill {
padding: 4px 9px;
font-size: 12px;
font-variant-numeric: tabular-nums;
color: var(--accent);
white-space: nowrap;
background: #15241c;
border: 1px solid #23402f;
border-radius: 999px;
}
.banner {
width: 100%;
padding: 12px 14px;
font-size: 14px;
color: #bfe8ce;
text-align: left;
cursor: pointer;
background: linear-gradient(180deg, #1d2f24, #15241c);
border: 1px solid #2b4a36;
border-radius: 14px;
}
/* Hero ------------------------------------------------------------------ */
.hero {
display: flex;
flex-direction: column;
gap: 16px;
align-items: center;
padding: 22px 16px 18px;
}
.hero-ring {
position: relative;
display: grid;
place-items: center;
width: 168px;
height: 168px;
}
.ring {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
transform: rotate(-90deg);
}
.ring circle {
fill: none;
stroke-width: 10;
stroke-linecap: round;
}
.ring-bg {
stroke: #1d2833;
}
.ring-fg {
stroke: var(--accent);
transition: stroke-dashoffset 0.45s ease;
}
.ring-fg.over {
stroke: var(--warn);
}
.hero-center {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
}
.hero-num {
font-size: 38px;
font-weight: 700;
line-height: 1;
letter-spacing: -0.03em;
font-variant-numeric: tabular-nums;
}
.hero-label {
font-size: 11px;
letter-spacing: 0.08em;
color: var(--muted);
text-transform: uppercase;
}
.hero-stats {
display: flex;
gap: 26px;
}
.hero-stats div {
display: flex;
flex-direction: column;
gap: 2px;
align-items: center;
}
.hero-stats span {
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.hero-stats strong {
font-size: 15px;
font-variant-numeric: tabular-nums;
}
/* Macros ---------------------------------------------------------------- */
.macro + .macro {
margin-top: 12px;
}
.macro .row {
margin-bottom: 6px;
font-size: 13px;
}
.track {
height: 8px;
overflow: hidden;
background: #1b2530;
border-radius: 999px;
}
.track span {
display: block;
height: 100%;
background: linear-gradient(90deg, var(--accent-strong), var(--accent));
border-radius: 999px;
transition: width 0.4s ease;
}
.track.carbs span {
background: linear-gradient(90deg, #3b7bbf, var(--blue));
}
.track.fat span {
background: linear-gradient(90deg, #b3813c, var(--warn));
}
.micro {
margin: 14px 0 0;
font-size: 12px;
}
/* Entries --------------------------------------------------------------- */
.entry-list {
margin: 8px 0 0;
padding: 0;
list-style: none;
}
.entry {
display: flex;
gap: 10px;
align-items: center;
padding: 10px 0;
border-top: 1px solid var(--line);
}
.entry:first-child {
border-top: 0;
}
.entry-main {
flex: 1;
min-width: 0;
}
.entry-name {
display: block;
overflow: hidden;
font-size: 14px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.entry-meta {
display: block;
margin-top: 2px;
font-size: 12px;
color: var(--muted);
}
.entry-kcal {
font-size: 14px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.x {
padding: 2px 6px;
font-size: 20px;
line-height: 1;
color: #5f6d7a;
background: none;
border: 0;
cursor: pointer;
}
.empty {
margin: 10px 0 0;
font-size: 14px;
}
.meal h2 {
margin: 0;
}
.steps-row {
margin-top: 10px;
}
/* Forms ----------------------------------------------------------------- */
.row-form {
display: flex;
gap: 8px;
align-items: center;
margin-top: 10px;
}
.row-form input,
.row-form select {
flex: 1;
min-width: 0;
}
input,
select,
button {
font: inherit;
}
input,
select {
width: 100%;
padding: 11px 12px;
font-size: 16px;
color: var(--text);
background: #0d141b;
border: 1px solid var(--line);
border-radius: 12px;
outline: none;
}
input:focus,
select:focus {
border-color: var(--accent);
}
select {
padding-right: 34px;
appearance: none;
background-image:
linear-gradient(45deg, transparent 50%, var(--muted) 50%),
linear-gradient(135deg, var(--muted) 50%, transparent 50%);
background-repeat: no-repeat;
background-position: calc(100% - 18px) 50%, calc(100% - 13px) 50%;
background-size: 5px 5px, 5px 5px;
}
.btn {
padding: 11px 14px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
cursor: pointer;
background: #1b2530;
border: 1px solid #26333f;
border-radius: 12px;
}
.btn.primary {
color: #062014;
background: linear-gradient(180deg, #48c98a, var(--accent-strong));
border-color: #3fbc82;
}
.btn.ghost {
color: var(--accent);
background: transparent;
border-color: #2a4a39;
}
.btn.small {
padding: 8px 12px;
font-size: 14px;
}
.btn.block {
width: 100%;
margin-top: 10px;
}
.btn:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 8px;
}
.chip {
padding: 7px 11px;
font-size: 13px;
color: var(--text);
cursor: pointer;
background: #16202a;
border: 1px solid var(--line);
border-radius: 999px;
}
.form-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.field {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
color: var(--muted);
}
.span-2 {
grid-column: span 2;
}
/* Scan ------------------------------------------------------------------ */
.segmented {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 4px;
padding: 4px;
background: #121a22;
border: 1px solid var(--line);
border-radius: 14px;
}
.segmented button {
padding: 9px;
font-weight: 600;
color: var(--muted);
cursor: pointer;
background: transparent;
border: 0;
border-radius: 11px;
}
.segmented button.is-active {
color: var(--text);
background: #1d2a35;
}
.scan-pane {
display: grid;
gap: 12px;
}
.camera-box {
display: grid;
gap: 8px;
margin-bottom: 10px;
}
.camera-box video {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
background: #000;
border-radius: 12px;
}
.or {
display: flex;
align-items: center;
gap: 10px;
margin: 12px 0 2px;
font-size: 12px;
color: var(--muted);
}
.or::before,
.or::after {
flex: 1;
height: 1px;
content: "";
background: var(--line);
}
.product {
display: grid;
gap: 12px;
}
.product-head {
display: flex;
gap: 12px;
align-items: flex-start;
}
.product-img {
flex: none;
width: 64px;
height: 64px;
object-fit: cover;
background: #0d141b;
border-radius: 12px;
}
.product h3 {
margin: 0 0 4px;
}
.product-kcal {
margin-left: auto;
font-weight: 600;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.unit {
font-size: 13px;
color: var(--muted);
}
#searchResults {
display: grid;
gap: 8px;
}
.result {
display: flex;
gap: 10px;
align-items: center;
padding: 10px;
color: inherit;
text-align: left;
cursor: pointer;
background: #121a22;
border: 1px solid var(--line);
border-radius: 14px;
}
.result img,
.result-placeholder {
flex: none;
width: 46px;
height: 46px;
object-fit: cover;
background: #0d141b;
border-radius: 10px;
}
.result-main {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
}
.result strong {
overflow: hidden;
font-size: 14px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.pad {
padding: 8px 2px;
}
/* Plan ------------------------------------------------------------------ */
.plan-summary h2 {
margin: 0;
}
.plan-summary p {
margin: 8px 0 10px;
font-size: 13px;
}
.ingredients {
margin: 8px 0 12px;
font-size: 13px;
line-height: 1.5;
color: var(--muted);
}
/* Profile --------------------------------------------------------------- */
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin: 12px 0 0;
}
.stats div {
padding: 10px;
background: #0f161d;
border: 1px solid var(--line);
border-radius: 12px;
}
.stats dt {
font-size: 12px;
color: var(--muted);
}
.stats dd {
margin: 3px 0 0;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.small-print h2 {
margin-bottom: 10px;
}
.small-print p {
font-size: 13px;
line-height: 1.55;
}
.small-print p.small {
margin-bottom: 0;
}
code {
padding: 1px 5px;
font-size: 0.92em;
background: #0d141b;
border-radius: 6px;
}
pre {
padding: 12px;
overflow-x: auto;
font-size: 12.5px;
line-height: 1.5;
background: #0d141b;
border: 1px solid var(--line);
border-radius: 12px;
}
pre code {
padding: 0;
}
/* Tab bar + toast ------------------------------------------------------- */
.tabbar {
position: fixed;
right: 0;
bottom: 0;
left: 0;
z-index: 30;
display: flex;
justify-content: space-around;
gap: 4px;
padding: 8px 8px calc(8px + env(safe-area-inset-bottom, 0px));
background: rgba(12, 17, 23, 0.94);
backdrop-filter: blur(16px);
border-top: 1px solid var(--line);
}
.tab {
display: flex;
flex-direction: column;
gap: 3px;
align-items: center;
min-width: 64px;
padding: 6px 14px;
font-size: 11px;
font-weight: 600;
color: var(--muted);
cursor: pointer;
background: none;
border: 0;
border-radius: 12px;
}
.tab svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.tab.is-active {
color: var(--accent);
}
.toast {
position: fixed;
bottom: calc(84px + env(safe-area-inset-bottom, 0px));
left: 50%;
z-index: 50;
max-width: calc(100vw - 32px);
padding: 10px 16px;
font-size: 14px;
text-align: center;
pointer-events: none;
opacity: 0;
background: #1d2a35;
border: 1px solid #2b3b48;
border-radius: 12px;
transform: translate(-50%, 16px);
transition: opacity 0.2s ease, transform 0.2s ease;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
.toast.error {
background: #2a1717;
border-color: #5a2a2a;
}
@media (min-width: 640px) {
main {
padding-top: 28px;
}
}
+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 };
+69
View File
@@ -0,0 +1,69 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { createParser } = require('../public/health');
const XML = `<?xml version="1.0" encoding="UTF-8"?>
<HealthData locale="en_US">
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="iPhone" unit="count"
creationDate="2026-11-06 08:00:00 -0700" startDate="2026-11-06 07:00:00 -0700"
endDate="2026-11-06 08:00:00 -0700" value="1200"/>
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="Watch" unit="count"
startDate="2026-11-06 09:00:00 -0700" endDate="2026-11-06 10:00:00 -0700" value="800"/>
<Record type="HKQuantityTypeIdentifierActiveEnergyBurned" sourceName="Watch" unit="kcal"
startDate="2026-11-06 09:00:00 -0700" endDate="2026-11-06 10:00:00 -0700" value="450"/>
<Record type="HKQuantityTypeIdentifierStepCount" sourceName="iPhone" unit="count"
startDate="2026-11-05 12:00:00 -0700" endDate="2026-11-05 13:00:00 -0700" value="5000"/>
<Workout workoutActivityType="HKWorkoutActivityTypeRunning" duration="32.5"
totalEnergyBurned="310" startDate="2026-11-06 07:12:00 -0700"
endDate="2026-11-06 07:44:30 -0700"/>
<Workout workoutActivityType="HKWorkoutActivityTypeTraditionalStrengthTraining"
startDate="2026-11-05 18:00:00 -0700" endDate="2026-11-05 18:45:00 -0700"/>
</HealthData>`;
test('sums step records per day and maps workouts', () => {
const parser = createParser({ since: '2026-11-05' });
parser.push(XML);
const result = parser.finish();
assert.deepEqual(
result.days.sort((a, b) => a.date.localeCompare(b.date)),
[{ date: '2026-11-05', steps: 5000 }, { date: '2026-11-06', steps: 2000 }]
);
const running = result.workouts.find((workout) => workout.name === 'Running');
assert.equal(running.kcal, 310);
assert.equal(running.minutes, 32.5);
assert.equal(running.met, 9);
const strength = result.workouts.find((workout) => workout.name === 'Strength training');
assert.equal(strength.kcal, 0);
assert.equal(strength.minutes, 45);
assert.equal(strength.met, 5);
});
test('ignores records before the requested range', () => {
const parser = createParser({ since: '2026-11-06' });
parser.push(XML);
const result = parser.finish();
assert.deepEqual(result.days, [{ date: '2026-11-06', steps: 2000 }]);
assert.equal(result.workouts.length, 1);
});
test('handles tags split across chunks', () => {
const whole = createParser();
whole.push(XML);
const expected = whole.finish();
const chunked = createParser();
for (let offset = 0; offset < XML.length; offset += 97) {
chunked.push(XML.slice(offset, offset + 97));
}
const actual = chunked.finish();
const byDate = (days) => days.sort((a, b) => a.date.localeCompare(b.date));
assert.deepEqual(byDate(actual.days), byDate(expected.days));
assert.equal(actual.workouts.length, expected.workouts.length);
});
+131
View File
@@ -0,0 +1,131 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const {
bmrKcal, kcalFromSteps, kcalFromExercise, dailyTargets,
imperialToMetric, metricToImperial, roundLbWeek,
KCAL_PER_LB, KCAL_PER_KG, LB_PER_KG,
} = require('../server/energy');
test('imperial <-> metric conversions', () => {
const m = imperialToMetric({ feet: 5, inches: 9, pounds: 165 });
assert.equal(m.heightCm, Math.round(69 * 2.54 * 100) / 100);
assert.equal(m.weightKg, Math.round(165 / 2.20462 * 100) / 100);
const imp = metricToImperial({ weightKg: 75, heightCm: 175 });
assert.equal(imp.pounds, Math.round(75 * 2.20462 * 10) / 10);
assert.equal(imp.feet, Math.floor(Math.round(175 / 2.54) / 12));
assert.equal(imp.inches, Math.round(175 / 2.54) % 12);
});
test('Mifflin-St Jeor BMR for men and women (metric inputs)', () => {
assert.equal(bmrKcal({ sex: 'male', weightKg: 75, heightCm: 175, age: 30 }), 1699);
assert.equal(bmrKcal({ sex: 'female', weightKg: 60, heightCm: 165, age: 30 }), 1320);
});
test('BMR from imperial profile rounds to same value', () => {
const m = imperialToMetric({ feet: 5, inches: 9, pounds: 165 });
assert.equal(bmrKcal({ sex: 'male', weightKg: m.weightKg, heightCm: m.heightCm, age: 30 }), 1699);
});
test('step calories scale with body weight', () => {
assert.equal(kcalFromSteps(10000, 75), 375);
assert.equal(kcalFromSteps(10000, 60), 300);
assert.equal(kcalFromSteps(0, 75), 0);
});
test('exercise calories use MET values', () => {
assert.equal(kcalFromExercise({ met: 8, minutes: 45, weightKg: 75 }), 473);
assert.equal(kcalFromExercise({ met: 2.5, minutes: 60, weightKg: 75 }), 197);
});
test('daily targets treat 1.0 lb/week as ~3500 kcal/week deficit', () => {
const profile = {
sex: 'male', weight_kg: 165 * LB_PER_KG, height_cm: (5 * 12 + 9) * 2.54,
age: 30, goal: 'maintain', rate_lb_week: 1.0,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.equal(targets.rateLbWeek, 1);
assert.ok(Math.abs(targets.adjustKcal + 500) <= 1);
});
test('daily targets treat 1.5 lb/week as ~5250 kcal/week deficit', () => {
const profile = {
sex: 'male', weight_kg: 165 * LB_PER_KG, height_cm: (5 * 12 + 9) * 2.54,
age: 30, goal: 'maintain', rate_lb_week: 1.5,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.equal(targets.rateLbWeek, 1.5);
assert.ok(Math.abs(targets.adjustKcal + 750) <= 1);
});
test('daily targets with kg/week still work via rate_kg_week', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'lose', rate_kg_week: 0.5, rate_lb_week: 0, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
// With only rate_kg_week provided, rateLbWeek is the rounded lb equivalent.
assert.ok(Math.abs(targets.rateLbWeek - (0.5 * LB_PER_KG)) < 0.05);
});
test('rate_lb_week is preserved when provided, with kg/week override', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'lose', rate_lb_week: 1.25, rate_kg_week: 0.5, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 0, exerciseKcal: 0 });
// rate_kg_week is also provided, so it wins and rate_lb_week is ignored.
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
assert.ok(Math.abs(targets.rateLbWeek - (0.5 * LB_PER_KG)) < 0.05);
});
test('daily targets add baseline, steps and workouts', () => {
const profile = {
sex: 'male', weight_kg: 75, height_cm: 175, age: 30,
goal: 'maintain', rate_lb_week: 0, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 10000, exerciseKcal: 473 });
assert.equal(targets.bmrKcal, 1699);
assert.equal(targets.basalKcal, 2039);
assert.equal(targets.stepKcal, 375);
assert.equal(targets.exerciseKcal, 473);
assert.equal(targets.totalBurnKcal, 2887);
assert.equal(targets.adjustKcal, 0);
assert.equal(targets.targetKcal, 2887);
assert.equal(targets.protein_g, 120);
});
test('a weight-loss goal subtracts the weekly rate and respects the floor', () => {
const profile = {
sex: 'female', weight_kg: 60, height_cm: 165, age: 30,
goal: 'lose', rate_lb_week: 0.5 * 2.20462, protein_target_g: null,
};
const targets = dailyTargets(profile, { steps: 8000, exerciseKcal: 0 });
assert.ok(Math.abs(targets.adjustKcal + 550) <= 1);
assert.equal(targets.protein_g, Math.round(60 * 2.0));
assert.ok(targets.targetKcal >= 1200);
});
test('roundLbWeek snaps to nearest 0.5 lb', () => {
assert.equal(roundLbWeek(0.6), 0.5);
assert.equal(roundLbWeek(0.8), 1);
assert.equal(roundLbWeek(1.2), 1);
assert.equal(roundLbWeek(1.3), 1.5);
});
test('KCAL_PER_LB and KCAL_PER_KG are consistent', () => {
assert.equal(KCAL_PER_LB, 3500);
assert.ok(Math.abs(KCAL_PER_KG - 3500 * 2.20462) < 1e-6);
});
test('a custom protein target overrides the default', () => {
const profile = {
sex: 'male', weight_kg: 80, height_cm: 180, age: 40,
goal: 'maintain', rate_lb_week: 0, protein_target_g: 170,
};
assert.equal(dailyTargets(profile).protein_g, 170);
});
+101
View File
@@ -0,0 +1,101 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { parseHealthAutoExport, workoutMeta } = require('../server/health-auto-export');
const PAYLOAD = {
data: {
metrics: [
{
name: 'step_count',
units: 'count',
data: [
{ qty: 1200, date: '2026-11-06 09:00:00 -0700', source: 'iPhone' },
{ qty: 800, date: '2026-11-06 18:30:00 -0700', source: 'Watch' },
{ qty: 5000, date: '2026-11-05 12:00:00 -0700' },
],
},
{
name: 'heart_rate',
units: 'count/min',
data: [{ qty: 70, date: '2026-11-06 09:00:00 -0700' }],
},
],
workouts: [
{
id: '550e8400-e29b-41d4-a716-446655440000',
name: 'Running',
start: '2026-11-06 07:00:00 -0700',
end: '2026-11-06 07:30:00 -0700',
duration: 1800,
activeEnergyBurned: { qty: 350, units: 'kcal' },
},
{
id: 'workout-2',
name: 'Traditional Strength Training',
start: '2026-11-05 18:00:00 -0700',
end: '2026-11-05 18:45:00 -0700',
},
],
},
};
test('sums step samples per local day and ignores other metrics', () => {
const result = parseHealthAutoExport(PAYLOAD);
assert.deepEqual(
result.days.sort((a, b) => a.date.localeCompare(b.date)),
[{ date: '2026-11-05', steps: 5000 }, { date: '2026-11-06', steps: 2000 }]
);
});
test('uses v2 duration seconds and active energy', () => {
const result = parseHealthAutoExport(PAYLOAD);
const running = result.workouts.find((workout) => workout.name === 'Running');
assert.equal(running.minutes, 30);
assert.equal(running.kcal, 350);
assert.equal(running.met, 9);
assert.equal(running.externalId, 'hae:550e8400-e29b-41d4-a716-446655440000');
});
test('derives minutes from start/end and maps strength training', () => {
const result = parseHealthAutoExport(PAYLOAD);
const strength = result.workouts.find((workout) => workout.name === 'Strength training');
assert.equal(strength.minutes, 45);
assert.equal(strength.kcal, 0);
assert.equal(strength.met, 5);
assert.equal(strength.date, '2026-11-05');
});
test('accepts v1 energy fields and an intensity override', () => {
const result = parseHealthAutoExport({
data: {
workouts: [
{
name: 'Indoor Cycling',
start: '2026-11-06 06:00:00 -0800',
end: '2026-11-06 06:20:00 -0800',
activeEnergy: { qty: 180, units: 'kcal' },
intensity: { qty: 7.2, units: 'MET' },
},
],
},
});
assert.equal(result.workouts.length, 1);
assert.equal(result.workouts[0].name, 'Cycling');
assert.equal(result.workouts[0].minutes, 20);
assert.equal(result.workouts[0].kcal, 180);
assert.equal(result.workouts[0].met, 7.2);
});
test('handles payloads without a data wrapper and includes no bogus days', () => {
assert.deepEqual(parseHealthAutoExport({ metrics: [] }), { days: [], workouts: [] });
assert.deepEqual(parseHealthAutoExport(null), { days: [], workouts: [] });
const meta = workoutMeta('Functional Strength Training');
assert.equal(meta.name, 'Strength training');
assert.equal(meta.met, 5);
});
+50
View File
@@ -0,0 +1,50 @@
'use strict';
// Keep the module's SQLite cache out of the project data directory.
process.env.DATA_DIR = `${require('node:os').tmpdir()}/counter-test-${process.pid}`;
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeProduct } = require('../server/nutrition');
test('normalizes a typical Open Food Facts product', () => {
const product = normalizeProduct({
code: '1234567890123',
product_name: 'Test Yogurt',
brands: 'Acme, Other Label',
serving_quantity: '150',
serving_size: '1 pot (150 g)',
nutriments: {
'energy-kcal_100g': 72,
proteins_100g: 8.5,
carbohydrates_100g: 6.2,
fat_100g: 1.4,
fiber_100g: 0.4,
sugars_100g: 5.1,
sodium_100g: 0.05,
},
});
assert.equal(product.name, 'Test Yogurt');
assert.equal(product.brand, 'Acme');
assert.equal(product.servingGrams, 150);
assert.equal(product.per100g.kcal, 72);
assert.equal(product.per100g.protein_g, 8.5);
assert.equal(product.per100g.sodium_mg, 50);
});
test('falls back to kilojoules and salt when needed', () => {
const product = normalizeProduct({
code: '999',
product_name: 'Bread',
nutriments: { 'energy-kj_100g': 418.4, salt_100g: 1 },
});
assert.equal(product.per100g.kcal, 100);
assert.equal(product.per100g.sodium_mg, 400);
});
test('rejects products without usable energy data', () => {
assert.equal(normalizeProduct({ code: '1', product_name: 'Air', nutriments: {} }), null);
assert.equal(normalizeProduct(null), null);
});
+55
View File
@@ -0,0 +1,55 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { generatePlan, styleAllows } = require('../server/planner');
const { RECIPES } = require('../server/seed');
test('a plan covers every meal slot with distinct recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2200, proteinTarget: 140, style: 'any', recipes: RECIPES,
});
assert.deepEqual(plan.items.map((item) => item.meal), ['breakfast', 'lunch', 'dinner', 'snack']);
assert.equal(new Set(plan.items.map((item) => item.id)).size, 4);
assert.ok(plan.totals.kcal > 1500 && plan.totals.kcal < 3000, `plan was ${plan.totals.kcal} kcal`);
});
test('the same date always generates the same plan', () => {
const args = {
date: '2026-11-07', targetKcal: 2000, proteinTarget: 120, style: 'any', recipes: RECIPES,
};
assert.deepEqual(
generatePlan(args).items.map((item) => item.id),
generatePlan(args).items.map((item) => item.id)
);
});
test('a vegan plan only contains vegan recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2000, proteinTarget: 100, style: 'vegan', recipes: RECIPES,
});
assert.equal(plan.items.length, 4);
assert.ok(plan.items.every((item) => item.tags.includes('vegan')));
});
test('a high-protein plan favours protein-rich recipes', () => {
const plan = generatePlan({
date: '2026-11-07', targetKcal: 2000, proteinTarget: 160, style: 'high_protein', recipes: RECIPES,
});
assert.ok(plan.totals.protein_g > 100);
});
test('style filtering falls back to any recipe when nothing matches', () => {
const onlySnack = RECIPES.filter((recipe) => recipe.meal === 'snack' && recipe.tags.includes('vegan'));
const plan = generatePlan({
date: '2026-11-07', targetKcal: 1800, proteinTarget: 90, style: 'vegetarian', recipes: onlySnack,
});
assert.ok(plan.items.length >= 1);
});
test('styleAllows treats vegan as vegetarian and high protein by macro', () => {
assert.equal(styleAllows({ tags: ['vegan'], protein_g: 10 }, 'vegetarian'), true);
assert.equal(styleAllows({ tags: [], protein_g: 30 }, 'high_protein'), true);
assert.equal(styleAllows({ tags: ['vegetarian'], protein_g: 10 }, 'vegan'), false);
});