Calio/shared/domain.js
Elijah 80fc48b9f1
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m2s
Add barcode and nutrition label scanning
Barcode scanning
- Scan barcode in the food sheet reads UPC-A/E and EAN-13/8 live from
  the camera with ZXing WebAssembly (bundled, precached, CSP allows
  wasm), with photo and typed-digit fallbacks
- Lookups check saved foods first (offline), then local copies of USDA
  FoodData Central Branded Foods and Open Food Facts, then the live
  Open Food Facts API; API answers and misses are cached
- Server imports refresh in a low-priority child process: USDA when a
  new archive is published, Open Food Facts weekly by streaming its CSV
  export; each import builds a new table and swaps it in atomically
- Every available nutrient is kept: foods and entries gain optional
  barcode (GTIN-14) and extra nutrients, shown under More nutrients and
  included in JSON exports
- Settings shows the size, date and any error for each product copy

Label scanning
- Scan label sends a downscaled photo to the server, read with
  PaddleOCR PP-OCRv5 (server detection, English recognition) on ONNX
  Runtime CPU, about 1.3 s median
- Parser handles US/Canadian, linear, Spanish and EU per-100 g panels,
  tilted photos, OCR misspellings and %DV cross-checks
- Models are pinned and checksum-verified at image build time

Container
- Runtime moves to Debian slim for ONNX Runtime's glibc build; other
  platforms' binaries are pruned
- Smoke tests now read a fixture label inside the container
- README and Unraid docs cover disk use, network access and refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:41:44 -07:00

158 lines
4.4 KiB
JavaScript

import { z } from "zod";
import { nutrientKeyPattern } from "./nutrients.js";
export const metricKeys = [
"calories",
"protein",
"carbs",
"fat",
"fiber",
"sugar",
"sodium",
];
const amount = z.number().finite().min(0).max(100000);
export const nutrientsSchema = z
.object(Object.fromEntries(metricKeys.map((key) => [key, amount])))
.strict();
const date = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine((value) => {
const parsed = new Date(value + "T12:00:00Z");
return (
!Number.isNaN(+parsed) && parsed.toISOString().slice(0, 10) === value
);
}, "Invalid date");
const name = z.string().trim().min(1).max(160);
const food = z.object({
name,
serving: z.string().trim().min(1).max(100),
nutrients: nutrientsSchema,
barcode: z
.string()
.regex(/^\d{14}$/)
.optional(),
// Further nutrients per serving, keyed as in shared/nutrients.js.
extra: z
.record(z.string().regex(nutrientKeyPattern), amount)
.refine((value) => Object.keys(value).length <= 200, "Too many nutrients")
.optional(),
});
const entry = food
.extend({
date,
time: z
.string()
.regex(/^([01]\d|2[0-3]):[0-5]\d$/)
.optional(),
meal: z.enum(["Breakfast", "Lunch", "Dinner", "Snacks"]),
quantity: z.number().finite().positive().max(1000),
})
.strict();
const goal = z
.object({
enabled: z.boolean(),
target: z.number().finite().positive().max(100000),
})
.strict();
const settings = z
.object({
theme: z.enum(["system", "light", "dark"]),
accentColor: z
.string()
.regex(/^#[a-fA-F0-9]{6}$/)
.optional(),
unit: z.enum(["kg", "lb"]),
goals: z
.object(Object.fromEntries(metricKeys.map((key) => [key, goal])))
.strict(),
exportFormat: z.enum(["markdown", "csv", "json"]),
exportDays: z.enum(["7", "30", "90", "all"]),
exportMetrics: z.array(z.enum(metricKeys)).max(7).optional(),
exportWeight: z.boolean().optional(),
minimumAverageCalories: amount.optional(),
})
.strict();
export const recordSchema = z
.object({
id: z.string().regex(/^[\w-]{1,80}$/),
type: z.enum(["entry", "food", "plate", "weight", "settings"]),
updatedAt: z.string().datetime({ offset: false }),
deleted: z.boolean(),
data: z.unknown(),
})
.strict()
.superRefine((record, ctx) => {
if (record.type === "settings" && record.id !== "settings")
ctx.addIssue({
code: "custom",
message: "Settings must use the settings ID",
});
if (record.type !== "settings" && record.id === "settings")
ctx.addIssue({ code: "custom", message: "Reserved settings ID" });
const schema = {
entry,
food: food.strict(),
plate: z
.object({
name,
items: z
.array(
food
.extend({ quantity: z.number().finite().positive().max(1000) })
.strict(),
)
.min(1)
.max(100),
})
.strict(),
weight: z
.object({
date,
valueKg: z.number().finite().positive().max(1000),
notes: z.string().max(500),
})
.strict(),
settings,
}[record.type];
const result = schema.safeParse(record.data);
if (!result.success)
for (const issue of result.error.issues)
ctx.addIssue({
code: "custom",
message: issue.message,
path: ["data", ...issue.path],
});
});
// The full payload breaks same-millisecond ties identically on every device.
export function compareRecords(a, b) {
const timestamp = Date.parse(a.updatedAt) - Date.parse(b.updatedAt);
if (timestamp) return timestamp;
const left = JSON.stringify([a.deleted, a.data]);
const right = JSON.stringify([b.deleted, b.data]);
return left === right ? 0 : left > right ? 1 : -1;
}
export function emptyNutrients() {
return Object.fromEntries(metricKeys.map((k) => [k, 0]));
}
export function totalNutrients(entries) {
const total = emptyNutrients();
for (const item of entries)
for (const key of metricKeys)
total[key] += (item.nutrients[key] || 0) * (item.quantity ?? 1);
return total;
}
export const defaultSettings = {
theme: "system",
accentColor: "#8391ed",
unit: "lb",
exportFormat: "markdown",
exportDays: "30",
goals: Object.fromEntries(
metricKeys.map((key, i) => [
key,
{ enabled: i < 4, target: [2000, 120, 250, 65, 30, 50, 2300][i] },
]),
),
};