mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-15 23:12:04 +00:00
chore(release): v1.4.25
Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites). See CHANGELOG.md for the full per-section delta.
This commit is contained in:
1 parent
de0689e419
commit
17b8d8d2c2
528 files changed
+104033
-6524
No files matched your search
@@ -21,11 +21,24 @@ describe("coachPrefsSchema", () => {
|
||||
verbosity: "brief" as const,
|
||||
excludeMetrics: ["bp", "weight"] as const,
|
||||
showEvidenceByDefault: true,
|
||||
defaultWindow: "last30days" as const,
|
||||
};
|
||||
const out = coachPrefsSchema.parse(input);
|
||||
expect(out).toEqual(input);
|
||||
});
|
||||
|
||||
// v1.4.25 W5 — defaultWindow added. Missing key → fallback to
|
||||
// "allTime" so the legacy persisted shape stays representative.
|
||||
it("fills in defaultWindow=allTime when the key is missing", () => {
|
||||
const out = coachPrefsSchema.parse({});
|
||||
expect(out.defaultWindow).toBe("allTime");
|
||||
});
|
||||
|
||||
it("rejects unknown defaultWindow values", () => {
|
||||
const result = coachPrefsSchema.safeParse({ defaultWindow: "lifetime" });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects unknown tone values", () => {
|
||||
const result = coachPrefsSchema.safeParse({ tone: "stoic" });
|
||||
expect(result.success).toBe(false);
|
||||
@@ -82,7 +95,21 @@ describe("parseCoachPrefs", () => {
|
||||
verbosity: "default" as const,
|
||||
excludeMetrics: ["mood" as const],
|
||||
showEvidenceByDefault: true,
|
||||
defaultWindow: "last90days" as const,
|
||||
};
|
||||
expect(parseCoachPrefs(input)).toEqual(input);
|
||||
});
|
||||
|
||||
it("fills defaultWindow=allTime when older persisted rows are missing it", () => {
|
||||
// Legacy v1.4.23/v1.4.24 persisted shape without `defaultWindow`.
|
||||
// Defaulting is backwards-compatible — the row keeps reading as
|
||||
// "all time" until the user picks a tighter default in the cog.
|
||||
const legacy = {
|
||||
tone: "warm" as const,
|
||||
verbosity: "default" as const,
|
||||
excludeMetrics: [] as const,
|
||||
showEvidenceByDefault: false,
|
||||
};
|
||||
expect(parseCoachPrefs(legacy).defaultWindow).toBe("allTime");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
doctorReportPrefsSchema,
|
||||
parseDoctorReportPrefs,
|
||||
resolveDoctorReportPrefs,
|
||||
} from "../doctor-report-prefs";
|
||||
|
||||
/**
|
||||
* v1.4.25 W6c — per-user Doctor-Report section toggles.
|
||||
*/
|
||||
describe("doctorReportPrefsSchema", () => {
|
||||
it("accepts an empty object (every key is optional)", () => {
|
||||
const out = doctorReportPrefsSchema.parse({});
|
||||
expect(out).toEqual({});
|
||||
});
|
||||
|
||||
it("accepts the full shape and round-trips it", () => {
|
||||
const input = {
|
||||
bp: true,
|
||||
weight: false,
|
||||
pulse: true,
|
||||
bmi: true,
|
||||
mood: false,
|
||||
compliance: true,
|
||||
sleep: false,
|
||||
};
|
||||
const out = doctorReportPrefsSchema.parse(input);
|
||||
expect(out).toEqual(input);
|
||||
});
|
||||
|
||||
it("accepts a partial update (only the toggled keys)", () => {
|
||||
const out = doctorReportPrefsSchema.parse({ mood: true });
|
||||
expect(out).toEqual({ mood: true });
|
||||
});
|
||||
|
||||
it("rejects a non-boolean value", () => {
|
||||
const result = doctorReportPrefsSchema.safeParse({ bp: "yes" });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseDoctorReportPrefs", () => {
|
||||
it("returns defaults for null input", () => {
|
||||
expect(parseDoctorReportPrefs(null)).toEqual(DEFAULT_DOCTOR_REPORT_PREFS);
|
||||
});
|
||||
|
||||
it("returns defaults for undefined input", () => {
|
||||
expect(parseDoctorReportPrefs(undefined)).toEqual(
|
||||
DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults mood to OFF (privacy directive per Marc)", () => {
|
||||
const out = parseDoctorReportPrefs(null);
|
||||
expect(out.mood).toBe(false);
|
||||
});
|
||||
|
||||
it("fills missing keys from defaults", () => {
|
||||
const out = parseDoctorReportPrefs({ bp: false });
|
||||
expect(out).toEqual({
|
||||
...DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
bp: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns defaults for malformed input (forward-compat fallback)", () => {
|
||||
expect(parseDoctorReportPrefs({ bp: "nope" })).toEqual(
|
||||
DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
);
|
||||
expect(parseDoctorReportPrefs("not an object")).toEqual(
|
||||
DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDoctorReportPrefs", () => {
|
||||
it("layers a partial update over current persisted values", () => {
|
||||
const current = {
|
||||
bp: false,
|
||||
weight: false,
|
||||
pulse: false,
|
||||
bmi: false,
|
||||
mood: true,
|
||||
compliance: false,
|
||||
sleep: false,
|
||||
};
|
||||
const out = resolveDoctorReportPrefs(current, { mood: false });
|
||||
expect(out).toEqual({ ...current, mood: false });
|
||||
});
|
||||
|
||||
it("layers a partial update over defaults when current is null", () => {
|
||||
const out = resolveDoctorReportPrefs(null, { mood: true });
|
||||
expect(out).toEqual({ ...DEFAULT_DOCTOR_REPORT_PREFS, mood: true });
|
||||
});
|
||||
});
|
||||
@@ -130,5 +130,47 @@ describe("measurement validation", () => {
|
||||
});
|
||||
expect(parsed.success).toBe(false);
|
||||
});
|
||||
|
||||
// v1.4.25 W10 reconcile (code-review M4): `deviceType` was a
|
||||
// batch-only field; the single-entry schema silently dropped it.
|
||||
// Now it parses through so the column is populated whether the
|
||||
// client posts one row or many.
|
||||
it("accepts an optional deviceType tag and surfaces it on the parsed value", () => {
|
||||
const parsed = createMeasurementSchema.safeParse({
|
||||
...validBase,
|
||||
type: "WEIGHT",
|
||||
value: 82,
|
||||
deviceType: "scale",
|
||||
});
|
||||
expect(parsed.success).toBe(true);
|
||||
if (parsed.success) {
|
||||
expect(parsed.data.deviceType).toBe("scale");
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts a null deviceType so a client can explicitly clear the column", () => {
|
||||
const parsed = createMeasurementSchema.safeParse({
|
||||
...validBase,
|
||||
type: "WEIGHT",
|
||||
value: 82,
|
||||
deviceType: null,
|
||||
});
|
||||
expect(parsed.success).toBe(true);
|
||||
if (parsed.success) {
|
||||
expect(parsed.data.deviceType).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("treats a missing deviceType as undefined (back-compat with pre-W10 clients)", () => {
|
||||
const parsed = createMeasurementSchema.safeParse({
|
||||
...validBase,
|
||||
type: "WEIGHT",
|
||||
value: 82,
|
||||
});
|
||||
expect(parsed.success).toBe(true);
|
||||
if (parsed.success) {
|
||||
expect(parsed.data.deviceType).toBeUndefined();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,372 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_DEVICE_TYPE_PRIORITY,
|
||||
DEFAULT_SOURCE_PRIORITY,
|
||||
SOURCE_PRIORITY_METRIC_KEYS,
|
||||
deviceTypeEnum,
|
||||
getDeviceTypeLadder,
|
||||
getSourceLadder,
|
||||
normalizeDeviceType,
|
||||
parseSourcePriority,
|
||||
sourcePrioritySchema,
|
||||
} from "../source-priority";
|
||||
|
||||
/**
|
||||
* v1.4.25 W5e — per-user, per-metric-class source-priority foundation.
|
||||
* v1.4.25 W8c — two-axis extension: `metricPriority` + `deviceTypePriority`.
|
||||
*/
|
||||
describe("sourcePrioritySchema", () => {
|
||||
it("accepts an empty object (every key is optional)", () => {
|
||||
const result = sourcePrioritySchema.safeParse({});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a partial flat shape (one metric class only) — W5e compat", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
weight: ["WITHINGS", "MANUAL"],
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.weight).toEqual(["WITHINGS", "MANUAL"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the W8c nested `metricPriority` shape", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
metricPriority: {
|
||||
weight: ["MANUAL", "WITHINGS"],
|
||||
steps: ["WITHINGS", "APPLE_HEALTH"],
|
||||
},
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.metricPriority?.weight).toEqual([
|
||||
"MANUAL",
|
||||
"WITHINGS",
|
||||
]);
|
||||
expect(result.data.metricPriority?.steps).toEqual([
|
||||
"WITHINGS",
|
||||
"APPLE_HEALTH",
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the W8c `deviceTypePriority` global default", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
deviceTypePriority: {
|
||||
default: ["watch", "phone", "ring"],
|
||||
},
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
expect(result.data.deviceTypePriority?.default).toEqual([
|
||||
"watch",
|
||||
"phone",
|
||||
"ring",
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts the W8c `deviceTypePriority` per-metric override", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
deviceTypePriority: {
|
||||
default: ["watch", "ring", "phone"],
|
||||
ACTIVITY_STEPS: ["phone", "watch"],
|
||||
WEIGHT: ["scale"],
|
||||
},
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
if (result.success) {
|
||||
// The catchall path stores per-metric overrides under their
|
||||
// MeasurementType-enum key.
|
||||
expect(result.data.deviceTypePriority?.ACTIVITY_STEPS).toEqual([
|
||||
"phone",
|
||||
"watch",
|
||||
]);
|
||||
expect(result.data.deviceTypePriority?.WEIGHT).toEqual(["scale"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts both axes in the same payload", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
metricPriority: {
|
||||
weight: ["MANUAL", "WITHINGS"],
|
||||
},
|
||||
deviceTypePriority: {
|
||||
default: ["watch", "ring"],
|
||||
},
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an unknown source string", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
weight: ["FITBIT", "WITHINGS"],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects an unknown device-type string", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
deviceTypePriority: {
|
||||
default: ["fitbit-tracker"],
|
||||
},
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects more than 8 sources in a single metric class", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
weight: [
|
||||
"WITHINGS",
|
||||
"APPLE_HEALTH",
|
||||
"MANUAL",
|
||||
"IMPORT",
|
||||
"WITHINGS",
|
||||
"APPLE_HEALTH",
|
||||
"MANUAL",
|
||||
"IMPORT",
|
||||
"WITHINGS",
|
||||
],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects a non-array value for a metric class", () => {
|
||||
const result = sourcePrioritySchema.safeParse({
|
||||
weight: "WITHINGS",
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deviceTypeEnum", () => {
|
||||
it("accepts every documented device-type slot", () => {
|
||||
for (const value of [
|
||||
"watch",
|
||||
"band",
|
||||
"ring",
|
||||
"phone",
|
||||
"scale",
|
||||
"other",
|
||||
"unknown",
|
||||
] as const) {
|
||||
expect(deviceTypeEnum.safeParse(value).success).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("DEFAULT_SOURCE_PRIORITY", () => {
|
||||
it("covers every metric key declared in SOURCE_PRIORITY_METRIC_KEYS", () => {
|
||||
// A new metric class added to the constant list without a default
|
||||
// would silently read as `undefined` at the call site and crash
|
||||
// the aggregator — this guard makes that mismatch a test failure.
|
||||
for (const key of SOURCE_PRIORITY_METRIC_KEYS) {
|
||||
expect(
|
||||
DEFAULT_SOURCE_PRIORITY[key],
|
||||
`missing default for ${key}`,
|
||||
).toBeInstanceOf(Array);
|
||||
expect(DEFAULT_SOURCE_PRIORITY[key].length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("places WITHINGS first for point measurements (Marc directive)", () => {
|
||||
// Withings devices are the primary sensor for point readings; the
|
||||
// canonical row should come from the scale / cuff / ScanWatch /
|
||||
// Thermo rather than HealthKit's second-hand mirror.
|
||||
for (const key of [
|
||||
"weight",
|
||||
"bloodPressure",
|
||||
"pulse",
|
||||
"bodyFat",
|
||||
"bodyTemperature",
|
||||
"spo2",
|
||||
"vo2Max",
|
||||
] as const) {
|
||||
expect(DEFAULT_SOURCE_PRIORITY[key][0]).toBe("WITHINGS");
|
||||
}
|
||||
});
|
||||
|
||||
it("places APPLE_HEALTH first for cumulative metrics + HRV/sleep/RHR", () => {
|
||||
// HealthKit aggregates ScanWatch + iPhone sensors into a single
|
||||
// canonical stream and has higher resolution than Withings' nightly
|
||||
// summary for sleep stages / HRV / RHR.
|
||||
for (const key of [
|
||||
"steps",
|
||||
"activeEnergy",
|
||||
"walkingRunningDistance",
|
||||
"flightsClimbed",
|
||||
"sleep",
|
||||
"hrv",
|
||||
"restingHeartRate",
|
||||
] as const) {
|
||||
expect(DEFAULT_SOURCE_PRIORITY[key][0]).toBe("APPLE_HEALTH");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("DEFAULT_DEVICE_TYPE_PRIORITY", () => {
|
||||
it("is non-empty and contains every enum slot", () => {
|
||||
// The picker treats an unknown device-type as `"unknown"` — to
|
||||
// stay safe the constant must include the `unknown` slot or
|
||||
// legacy/NULL-tagged rows would never resolve a rank.
|
||||
expect(DEFAULT_DEVICE_TYPE_PRIORITY.length).toBe(7);
|
||||
expect(DEFAULT_DEVICE_TYPE_PRIORITY).toContain("unknown");
|
||||
});
|
||||
|
||||
it("places `watch` first (open-wearables-compatible default)", () => {
|
||||
expect(DEFAULT_DEVICE_TYPE_PRIORITY[0]).toBe("watch");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseSourcePriority", () => {
|
||||
it("returns defaults for null input", () => {
|
||||
const out = parseSourcePriority(null);
|
||||
expect(out).toMatchObject(DEFAULT_SOURCE_PRIORITY);
|
||||
expect(out.metricPriority).toEqual(DEFAULT_SOURCE_PRIORITY);
|
||||
expect(out.deviceTypePriority).toEqual({});
|
||||
});
|
||||
|
||||
it("returns defaults for undefined input", () => {
|
||||
const out = parseSourcePriority(undefined);
|
||||
expect(out).toMatchObject(DEFAULT_SOURCE_PRIORITY);
|
||||
});
|
||||
|
||||
it("returns defaults for malformed input (forward-compat fallback)", () => {
|
||||
expect(parseSourcePriority({ weight: "WITHINGS" })).toMatchObject(
|
||||
DEFAULT_SOURCE_PRIORITY,
|
||||
);
|
||||
expect(parseSourcePriority("not an object")).toMatchObject(
|
||||
DEFAULT_SOURCE_PRIORITY,
|
||||
);
|
||||
});
|
||||
|
||||
it("merges a flat partial shape onto defaults (W5e compat)", () => {
|
||||
const partial = {
|
||||
weight: ["MANUAL", "WITHINGS"] as const,
|
||||
};
|
||||
const out = parseSourcePriority(partial);
|
||||
expect(out.weight).toEqual(["MANUAL", "WITHINGS"]);
|
||||
expect(out.metricPriority.weight).toEqual(["MANUAL", "WITHINGS"]);
|
||||
// Other keys keep their defaults.
|
||||
expect(out.steps).toEqual(DEFAULT_SOURCE_PRIORITY.steps);
|
||||
expect(out.bloodPressure).toEqual(DEFAULT_SOURCE_PRIORITY.bloodPressure);
|
||||
});
|
||||
|
||||
it("merges a W8c nested `metricPriority` onto defaults", () => {
|
||||
const partial = {
|
||||
metricPriority: {
|
||||
weight: ["MANUAL", "APPLE_HEALTH"] as const,
|
||||
steps: ["WITHINGS"] as const,
|
||||
},
|
||||
};
|
||||
const out = parseSourcePriority(partial);
|
||||
expect(out.metricPriority.weight).toEqual(["MANUAL", "APPLE_HEALTH"]);
|
||||
expect(out.metricPriority.steps).toEqual(["WITHINGS"]);
|
||||
// Unchanged metrics keep the constant default.
|
||||
expect(out.metricPriority.bloodPressure).toEqual(
|
||||
DEFAULT_SOURCE_PRIORITY.bloodPressure,
|
||||
);
|
||||
});
|
||||
|
||||
it("prefers W8c nested over W5e flat when both shapes are present", () => {
|
||||
// A user who edits the new UI ships the nested shape; if a
|
||||
// legacy/admin tool also stashed the flat shape, the nested wins.
|
||||
const out = parseSourcePriority({
|
||||
weight: ["WITHINGS"],
|
||||
metricPriority: {
|
||||
weight: ["MANUAL", "WITHINGS"],
|
||||
},
|
||||
});
|
||||
expect(out.weight).toEqual(["MANUAL", "WITHINGS"]);
|
||||
expect(out.metricPriority.weight).toEqual(["MANUAL", "WITHINGS"]);
|
||||
});
|
||||
|
||||
it("surfaces `deviceTypePriority` round-trip unchanged", () => {
|
||||
const out = parseSourcePriority({
|
||||
deviceTypePriority: {
|
||||
default: ["watch", "ring"],
|
||||
WEIGHT: ["scale"],
|
||||
},
|
||||
});
|
||||
expect(out.deviceTypePriority.default).toEqual(["watch", "ring"]);
|
||||
expect(out.deviceTypePriority.WEIGHT).toEqual(["scale"]);
|
||||
});
|
||||
|
||||
it("preserves a fully-specified flat shape (W5e back-compat path)", () => {
|
||||
const input = {
|
||||
...DEFAULT_SOURCE_PRIORITY,
|
||||
weight: ["MANUAL", "APPLE_HEALTH"] as const,
|
||||
};
|
||||
const out = parseSourcePriority(input);
|
||||
expect(out.weight).toEqual(["MANUAL", "APPLE_HEALTH"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeDeviceType", () => {
|
||||
it("returns the canonical value for every enum slot", () => {
|
||||
for (const value of [
|
||||
"watch",
|
||||
"band",
|
||||
"ring",
|
||||
"phone",
|
||||
"scale",
|
||||
"other",
|
||||
"unknown",
|
||||
] as const) {
|
||||
expect(normalizeDeviceType(value)).toBe(value);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns `unknown` for null / undefined / unknown strings", () => {
|
||||
expect(normalizeDeviceType(null)).toBe("unknown");
|
||||
expect(normalizeDeviceType(undefined)).toBe("unknown");
|
||||
expect(normalizeDeviceType("fitbit")).toBe("unknown");
|
||||
expect(normalizeDeviceType(42)).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSourceLadder + getDeviceTypeLadder helpers", () => {
|
||||
it("getSourceLadder reads the resolved metric ladder", () => {
|
||||
const resolved = parseSourcePriority({
|
||||
metricPriority: { weight: ["MANUAL"] },
|
||||
});
|
||||
expect(getSourceLadder(resolved, "weight")).toEqual(["MANUAL"]);
|
||||
expect(getSourceLadder(resolved, "bloodPressure")).toEqual(
|
||||
DEFAULT_SOURCE_PRIORITY.bloodPressure,
|
||||
);
|
||||
});
|
||||
|
||||
it("getDeviceTypeLadder prefers a per-metric override", () => {
|
||||
const resolved = parseSourcePriority({
|
||||
deviceTypePriority: {
|
||||
default: ["phone", "watch"],
|
||||
WEIGHT: ["scale", "watch"],
|
||||
},
|
||||
});
|
||||
expect(getDeviceTypeLadder(resolved, "WEIGHT")).toEqual([
|
||||
"scale",
|
||||
"watch",
|
||||
]);
|
||||
});
|
||||
|
||||
it("getDeviceTypeLadder falls back to the user default ladder", () => {
|
||||
const resolved = parseSourcePriority({
|
||||
deviceTypePriority: {
|
||||
default: ["phone", "watch"],
|
||||
},
|
||||
});
|
||||
expect(getDeviceTypeLadder(resolved, "ACTIVITY_STEPS")).toEqual([
|
||||
"phone",
|
||||
"watch",
|
||||
]);
|
||||
});
|
||||
|
||||
it("getDeviceTypeLadder falls back to the constant default ladder when nothing is set", () => {
|
||||
const resolved = parseSourcePriority(null);
|
||||
expect(getDeviceTypeLadder(resolved, "ACTIVITY_STEPS")).toEqual(
|
||||
DEFAULT_DEVICE_TYPE_PRIORITY,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createBatchWorkoutSchema,
|
||||
createWorkoutSchema,
|
||||
geoJsonLineStringSchema,
|
||||
MAX_ROUTE_POINTS,
|
||||
MAX_WORKOUTS_PER_BATCH,
|
||||
workoutRouteSamplesSchema,
|
||||
workoutSportTypeEnum,
|
||||
type CreateWorkoutInput,
|
||||
} from "../workout";
|
||||
|
||||
describe("workoutSportTypeEnum", () => {
|
||||
it("accepts every documented sport", () => {
|
||||
for (const sport of [
|
||||
"walking",
|
||||
"running",
|
||||
"cycling",
|
||||
"swimming",
|
||||
"hiit",
|
||||
"other",
|
||||
]) {
|
||||
expect(workoutSportTypeEnum.parse(sport)).toBe(sport);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an unknown sport", () => {
|
||||
expect(() => workoutSportTypeEnum.parse("teleportation")).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("geoJsonLineStringSchema", () => {
|
||||
it("accepts a valid GeoJSON LineString with lon/lat pairs", () => {
|
||||
const parsed = geoJsonLineStringSchema.parse({
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 49.452],
|
||||
[11.078, 49.453],
|
||||
],
|
||||
});
|
||||
expect(parsed.type).toBe("LineString");
|
||||
expect(parsed.coordinates).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("accepts coordinates with an altitude component", () => {
|
||||
const parsed = geoJsonLineStringSchema.parse({
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 49.452, 320.5],
|
||||
[11.078, 49.453, 322.1],
|
||||
],
|
||||
});
|
||||
expect(parsed.coordinates[0]).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("rejects a Point geometry", () => {
|
||||
expect(() =>
|
||||
geoJsonLineStringSchema.parse({
|
||||
type: "Point",
|
||||
coordinates: [11.077, 49.452],
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a single-point LineString", () => {
|
||||
expect(() =>
|
||||
geoJsonLineStringSchema.parse({
|
||||
type: "LineString",
|
||||
coordinates: [[11.077, 49.452]],
|
||||
}),
|
||||
).toThrow(/at least 2 points/);
|
||||
});
|
||||
|
||||
it("rejects out-of-bounds longitude / latitude", () => {
|
||||
expect(() =>
|
||||
geoJsonLineStringSchema.parse({
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[200, 49.452],
|
||||
[201, 49.453],
|
||||
],
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
geoJsonLineStringSchema.parse({
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 200],
|
||||
[11.078, 201],
|
||||
],
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("workoutRouteSamplesSchema", () => {
|
||||
it("accepts an array of timestamp + optional speed/hr entries", () => {
|
||||
const parsed = workoutRouteSamplesSchema.parse([
|
||||
{ t: "2026-05-14T07:00:00.000Z", speedMs: 3.2, hr: 142 },
|
||||
{ t: "2026-05-14T07:00:05.000Z" },
|
||||
]);
|
||||
expect(parsed).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects negative speed", () => {
|
||||
expect(() =>
|
||||
workoutRouteSamplesSchema.parse([
|
||||
{ t: "2026-05-14T07:00:00.000Z", speedMs: -1 },
|
||||
]),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("createWorkoutSchema", () => {
|
||||
const minimalRun: Record<string, unknown> = {
|
||||
sportType: "running",
|
||||
startedAt: "2026-05-14T06:30:00.000Z",
|
||||
endedAt: "2026-05-14T07:15:00.000Z",
|
||||
};
|
||||
|
||||
it("accepts a minimal workout payload", () => {
|
||||
const parsed = createWorkoutSchema.parse(minimalRun);
|
||||
expect(parsed.sportType).toBe("running");
|
||||
expect(parsed.startedAt).toBeInstanceOf(Date);
|
||||
expect(parsed.endedAt).toBeInstanceOf(Date);
|
||||
expect(parsed.source).toBe("MANUAL");
|
||||
});
|
||||
|
||||
it("accepts an Apple-Health-shaped HKWorkout payload", () => {
|
||||
const input: Record<string, unknown> = {
|
||||
sportType: "running",
|
||||
startedAt: "2026-05-14T06:30:00.000Z",
|
||||
endedAt: "2026-05-14T07:15:00.000Z",
|
||||
totalEnergyKcal: 412.3,
|
||||
totalDistanceM: 7_800,
|
||||
avgHeartRate: 154,
|
||||
maxHeartRate: 178,
|
||||
minHeartRate: 92,
|
||||
source: "APPLE_HEALTH",
|
||||
externalId: "B5F8-...-A3",
|
||||
metadata: { HKAverageMETs: 8.4, sourceBundleId: "com.apple.health" },
|
||||
route: {
|
||||
geometry: {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 49.452, 320.5],
|
||||
[11.078, 49.453, 322.1],
|
||||
],
|
||||
},
|
||||
sampleTimestamps: [
|
||||
{ t: "2026-05-14T06:30:00.000Z", speedMs: 3.2, hr: 142 },
|
||||
{ t: "2026-05-14T06:30:05.000Z", speedMs: 3.3, hr: 144 },
|
||||
],
|
||||
},
|
||||
};
|
||||
const parsed: CreateWorkoutInput = createWorkoutSchema.parse(input);
|
||||
expect(parsed.source).toBe("APPLE_HEALTH");
|
||||
expect(parsed.totalDistanceM).toBe(7_800);
|
||||
expect(parsed.route?.geometry.coordinates).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rejects an unknown sportType", () => {
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({ ...minimalRun, sportType: "fartlek" }),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a max heart rate below the resting floor", () => {
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({ ...minimalRun, maxHeartRate: 5 }),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects a route geometry that exceeds the per-route point cap", () => {
|
||||
// One past the cap — schema MUST reject. The cap exists so a single
|
||||
// pathological workout can't blow the 5 MB request-body ceiling on
|
||||
// its own; a desync between the schema cap and the route route's
|
||||
// expected-size accounting would silently degrade ingest.
|
||||
const coords: [number, number][] = [];
|
||||
for (let i = 0; i < MAX_ROUTE_POINTS + 1; i++) {
|
||||
coords.push([11 + i * 1e-6, 49 + i * 1e-6]);
|
||||
}
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({
|
||||
...minimalRun,
|
||||
route: {
|
||||
geometry: { type: "LineString", coordinates: coords },
|
||||
},
|
||||
}),
|
||||
).toThrow(/20000-point cap/);
|
||||
});
|
||||
|
||||
it("rejects a workout whose endedAt is before startedAt", () => {
|
||||
// Regression for the W16b ingest gate: a reversed pair produced a
|
||||
// negative `durationSec` that downstream consumers (PR detector,
|
||||
// weekly report) treated as a real zero — a fastest-5km PR of
|
||||
// zero seconds would lock in until manual cleanup. The schema
|
||||
// refuses the row at parse time.
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({
|
||||
...minimalRun,
|
||||
startedAt: "2026-05-14T07:15:00.000Z",
|
||||
endedAt: "2026-05-14T06:30:00.000Z",
|
||||
}),
|
||||
).toThrow(/endedAt must be strictly after startedAt/);
|
||||
});
|
||||
|
||||
it("rejects a zero-duration workout (endedAt === startedAt)", () => {
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({
|
||||
...minimalRun,
|
||||
startedAt: "2026-05-14T06:30:00.000Z",
|
||||
endedAt: "2026-05-14T06:30:00.000Z",
|
||||
}),
|
||||
).toThrow(/endedAt must be strictly after startedAt/);
|
||||
});
|
||||
|
||||
it("rejects a route whose sampleTimestamps length mismatches coordinates", () => {
|
||||
// Cross-field invariant: per-sample HR / speed must line up against
|
||||
// the parallel coordinate index, so a desynced pair silently
|
||||
// poisons downstream analytics. Hard-fail at parse time so the iOS
|
||||
// mapper surfaces the problem immediately.
|
||||
expect(() =>
|
||||
createWorkoutSchema.parse({
|
||||
...minimalRun,
|
||||
route: {
|
||||
geometry: {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 49.452],
|
||||
[11.078, 49.453],
|
||||
[11.079, 49.454],
|
||||
],
|
||||
},
|
||||
sampleTimestamps: [
|
||||
{ t: "2026-05-14T06:30:00.000Z" },
|
||||
{ t: "2026-05-14T06:30:05.000Z" },
|
||||
// missing third entry — desync the parser MUST catch
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toThrow(/sampleTimestamps length must match/);
|
||||
});
|
||||
|
||||
it("accepts a route when sampleTimestamps length equals coordinates length", () => {
|
||||
const parsed = createWorkoutSchema.parse({
|
||||
...minimalRun,
|
||||
route: {
|
||||
geometry: {
|
||||
type: "LineString",
|
||||
coordinates: [
|
||||
[11.077, 49.452],
|
||||
[11.078, 49.453],
|
||||
],
|
||||
},
|
||||
sampleTimestamps: [
|
||||
{ t: "2026-05-14T06:30:00.000Z", speedMs: 3.2, hr: 142 },
|
||||
{ t: "2026-05-14T06:30:05.000Z", speedMs: 3.3, hr: 144 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(parsed.route?.sampleTimestamps).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createBatchWorkoutSchema", () => {
|
||||
const minimalRun = (id: string) => ({
|
||||
sportType: "running",
|
||||
startedAt: "2026-05-14T06:30:00.000Z",
|
||||
endedAt: "2026-05-14T07:15:00.000Z",
|
||||
externalId: id,
|
||||
});
|
||||
|
||||
it("accepts a single-workout batch", () => {
|
||||
const parsed = createBatchWorkoutSchema.parse({
|
||||
workouts: [minimalRun("hk-uuid-001")],
|
||||
});
|
||||
expect(parsed.workouts).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts a batch at the cap (100 workouts)", () => {
|
||||
const workouts = Array.from(
|
||||
{ length: MAX_WORKOUTS_PER_BATCH },
|
||||
(_, i) => minimalRun(`hk-uuid-${i}`),
|
||||
);
|
||||
const parsed = createBatchWorkoutSchema.parse({ workouts });
|
||||
expect(parsed.workouts).toHaveLength(MAX_WORKOUTS_PER_BATCH);
|
||||
});
|
||||
|
||||
it("rejects a batch above the cap", () => {
|
||||
const workouts = Array.from(
|
||||
{ length: MAX_WORKOUTS_PER_BATCH + 1 },
|
||||
(_, i) => minimalRun(`hk-uuid-${i}`),
|
||||
);
|
||||
expect(() => createBatchWorkoutSchema.parse({ workouts })).toThrow();
|
||||
});
|
||||
|
||||
it("rejects an empty batch", () => {
|
||||
expect(() => createBatchWorkoutSchema.parse({ workouts: [] })).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -75,5 +75,10 @@ export const adminSettingsSchema = z
|
||||
reminderLateMinutes: z.number().int().min(15).max(480).optional(),
|
||||
reminderMissedMinutes: z.number().int().min(30).max(720).optional(),
|
||||
moodLogGlobal: z.boolean().optional(),
|
||||
// v1.4.25 W7 — server-wide default timezone for new signups
|
||||
// that don't carry a browser-detected zone. The route validates
|
||||
// against Intl.supportedValuesOf at runtime; this schema just
|
||||
// guards the shape + length.
|
||||
defaultUserTimezone: z.string().max(64).optional(),
|
||||
})
|
||||
.strict();
|
||||
@@ -16,6 +16,16 @@ export const registerSchema = z.object({
|
||||
PASSWORD_MIN_LENGTH,
|
||||
`Password must be at least ${PASSWORD_MIN_LENGTH} characters`,
|
||||
),
|
||||
/**
|
||||
* v1.4.25 W7 — browser-detected timezone. The signup form pulls
|
||||
* `Intl.DateTimeFormat().resolvedOptions().timeZone` and sends it
|
||||
* along; the server validates against the runtime IANA list and
|
||||
* falls back to the admin-configured server default
|
||||
* (`AppSettings.defaultUserTimezone`) when the value is invalid
|
||||
* or missing. Optional so legacy clients that predate v1.4.25
|
||||
* keep working.
|
||||
*/
|
||||
timezone: z.string().max(64).optional(),
|
||||
});
|
||||
|
||||
export const loginPasswordSchema = z.object({
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
* snapshot builder both read this shape — the snapshot must filter on
|
||||
* `excludeMetrics` BEFORE landing in the system prompt so the model
|
||||
* never sees data the user opted out of.
|
||||
*
|
||||
* v1.4.25 W5 — extended with `defaultWindow`. The picker lives in the
|
||||
* settings sheet; the drawer header carries a per-conversation override
|
||||
* pill so a single chat can narrow the window without flipping the
|
||||
* global default. The chat route folds the saved preference into the
|
||||
* snapshot scope when the client didn't supply a window override.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
@@ -52,6 +58,23 @@ export const coachExcludeMetricEnum = z.enum([
|
||||
]);
|
||||
export type CoachExcludeMetric = z.infer<typeof coachExcludeMetricEnum>;
|
||||
|
||||
/**
|
||||
* v1.4.25 W5 — default analysis window the Coach uses when the client
|
||||
* doesn't supply a per-conversation override. Mirrors
|
||||
* `CoachScopeWindow` (`src/lib/ai/coach/types.ts`) so the chat route
|
||||
* can fold the preference into `scope.window` without a translation
|
||||
* layer. The default stays `allTime` to preserve the v1.4.24 behaviour
|
||||
* — every legacy row reads as "no opinion" until the user explicitly
|
||||
* picks a tighter default.
|
||||
*/
|
||||
export const coachDefaultWindowEnum = z.enum([
|
||||
"last7days",
|
||||
"last30days",
|
||||
"last90days",
|
||||
"allTime",
|
||||
]);
|
||||
export type CoachDefaultWindow = z.infer<typeof coachDefaultWindowEnum>;
|
||||
|
||||
/**
|
||||
* Full preferences shape. Defaults are inlined into the schema so a
|
||||
* `safeParse({})` call returns the legacy v1.4.22 defaults — saves a
|
||||
@@ -62,6 +85,7 @@ export const coachPrefsSchema = z.object({
|
||||
verbosity: coachVerbosityEnum.default("default"),
|
||||
excludeMetrics: z.array(coachExcludeMetricEnum).max(9).default([]),
|
||||
showEvidenceByDefault: z.boolean().default(false),
|
||||
defaultWindow: coachDefaultWindowEnum.default("allTime"),
|
||||
});
|
||||
|
||||
export type CoachPrefs = z.infer<typeof coachPrefsSchema>;
|
||||
@@ -77,6 +101,7 @@ export const DEFAULT_COACH_PREFS: CoachPrefs = {
|
||||
verbosity: "default",
|
||||
excludeMetrics: [],
|
||||
showEvidenceByDefault: false,
|
||||
defaultWindow: "allTime",
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* v1.4.25 W6c — per-user Doctor-Report section toggles.
|
||||
*
|
||||
* Persisted as a Json blob on `User.doctorReportPrefsJson`. Null = the
|
||||
* documented defaults (every section ON except mood). The dialog reads
|
||||
* the row, lets the user flip checkboxes, and writes the chosen shape
|
||||
* back. The PDF generator + the report aggregator both consult the
|
||||
* shape: aggregator drops mood data entirely when `mood = false` so the
|
||||
* data never leaves the DB row (privacy-by-default), and the generator
|
||||
* skips each section whose flag is false at render time.
|
||||
*
|
||||
* The shape is intentionally additive — every new data type added to the
|
||||
* report grows the schema with a new optional flag and a new entry in
|
||||
* `DEFAULT_DOCTOR_REPORT_PREFS`. Forward-compat: an unknown / drifted
|
||||
* shape falls back to defaults rather than throwing.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
/**
|
||||
* Section toggle schema. Every key is optional so a partial update from
|
||||
* the dialog (e.g., "the user only flipped mood") doesn't have to
|
||||
* re-state every other flag. The route layer fills missing keys from the
|
||||
* defaults before persisting so the column shape stays stable.
|
||||
*/
|
||||
export const doctorReportPrefsSchema = z
|
||||
.object({
|
||||
bp: z.boolean(),
|
||||
weight: z.boolean(),
|
||||
pulse: z.boolean(),
|
||||
bmi: z.boolean(),
|
||||
mood: z.boolean(),
|
||||
compliance: z.boolean(),
|
||||
sleep: z.boolean(),
|
||||
})
|
||||
.partial();
|
||||
|
||||
export type DoctorReportPrefsInput = z.infer<typeof doctorReportPrefsSchema>;
|
||||
|
||||
/**
|
||||
* Fully-resolved section toggles. Every key required so the consumers
|
||||
* (PDF renderer + aggregator) don't have to thread an "is this key
|
||||
* present?" check through their render paths.
|
||||
*/
|
||||
export interface DoctorReportPrefs {
|
||||
bp: boolean;
|
||||
weight: boolean;
|
||||
pulse: boolean;
|
||||
bmi: boolean;
|
||||
mood: boolean;
|
||||
compliance: boolean;
|
||||
sleep: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Defaults applied when the user has never opened the dialog. Every
|
||||
* section is ON by default EXCEPT mood, which is opt-in per Marc's
|
||||
* privacy directive (2026-05-14): mental-health data should never appear
|
||||
* in a clinical PDF the user didn't explicitly check.
|
||||
*/
|
||||
export const DEFAULT_DOCTOR_REPORT_PREFS: DoctorReportPrefs = {
|
||||
bp: true,
|
||||
weight: true,
|
||||
pulse: true,
|
||||
bmi: true,
|
||||
mood: false, // privacy default per Marc
|
||||
compliance: true,
|
||||
sleep: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a row's `doctorReportPrefsJson` Json blob into a typed
|
||||
* `DoctorReportPrefs`, falling back to the documented defaults when the
|
||||
* row is null OR the persisted shape has drifted (a forward-compat field
|
||||
* rename, an admin-side hand-edit, etc.). Missing keys are filled from
|
||||
* the defaults so callers always get a fully-resolved object.
|
||||
*/
|
||||
export function parseDoctorReportPrefs(raw: unknown): DoctorReportPrefs {
|
||||
if (raw == null) return { ...DEFAULT_DOCTOR_REPORT_PREFS };
|
||||
const parsed = doctorReportPrefsSchema.safeParse(raw);
|
||||
if (!parsed.success) return { ...DEFAULT_DOCTOR_REPORT_PREFS };
|
||||
return {
|
||||
...DEFAULT_DOCTOR_REPORT_PREFS,
|
||||
...parsed.data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a partial input (typically from a PUT body) into the full
|
||||
* canonical shape, layering the supplied keys over the current
|
||||
* persisted row (or defaults when null). Keeps the route layer free of
|
||||
* merge plumbing.
|
||||
*/
|
||||
export function resolveDoctorReportPrefs(
|
||||
current: unknown,
|
||||
incoming: DoctorReportPrefsInput,
|
||||
): DoctorReportPrefs {
|
||||
const base = parseDoctorReportPrefs(current);
|
||||
return { ...base, ...incoming };
|
||||
}
|
||||
@@ -20,6 +20,18 @@ export const measurementTypeEnum = z.enum([
|
||||
"WALKING_RUNNING_DISTANCE",
|
||||
"VO2_MAX",
|
||||
"BODY_TEMPERATURE",
|
||||
// ── v1.4.25 W5d Withings full coverage ──
|
||||
"FAT_FREE_MASS",
|
||||
"FAT_MASS",
|
||||
"MUSCLE_MASS",
|
||||
"SKIN_TEMPERATURE",
|
||||
"PULSE_WAVE_VELOCITY",
|
||||
"VASCULAR_AGE",
|
||||
"VISCERAL_FAT",
|
||||
// ── v1.4.25 W8d Apple Health server-prep ──
|
||||
"AUDIO_EXPOSURE_ENV",
|
||||
"AUDIO_EXPOSURE_HEADPHONE",
|
||||
"TIME_IN_DAYLIGHT",
|
||||
]);
|
||||
|
||||
export const glucoseContextEnum = z.enum([
|
||||
@@ -68,6 +80,29 @@ const unitMap: Record<string, string> = {
|
||||
WALKING_RUNNING_DISTANCE: "m",
|
||||
VO2_MAX: "mL/(kg·min)",
|
||||
BODY_TEMPERATURE: "celsius",
|
||||
// ── v1.4.25 W5d Withings full coverage ──
|
||||
FAT_FREE_MASS: "kg",
|
||||
FAT_MASS: "kg",
|
||||
MUSCLE_MASS: "kg",
|
||||
// Distinct from BODY_TEMPERATURE — surface temps run ~32 °C; sharing
|
||||
// the bucket would corrupt analytics. Same canonical unit (°C).
|
||||
SKIN_TEMPERATURE: "celsius",
|
||||
PULSE_WAVE_VELOCITY: "m/s",
|
||||
VASCULAR_AGE: "years",
|
||||
// Withings reports visceral fat as a 1–12 rating, not a percent. The
|
||||
// string mirrors what Withings prints in Health Mate.
|
||||
VISCERAL_FAT: "rating",
|
||||
// ── v1.4.25 W8d Apple Health server-prep ──
|
||||
// Sound-pressure level — A-weighted decibels (dBA). HealthKit reports
|
||||
// both audio-exposure metrics in dBASPL; we store the unweighted "dBA"
|
||||
// label because the A-weighting is implicit (every HealthKit audio
|
||||
// sample carries it). 30 dBA = quiet bedroom; 140 dBA = pain threshold.
|
||||
AUDIO_EXPOSURE_ENV: "dBA",
|
||||
AUDIO_EXPOSURE_HEADPHONE: "dBA",
|
||||
// Daily-rollup pattern (one sample = one day's outdoor-light minutes).
|
||||
// 0–1440 covers the 24-hour day; in practice indoor users sit near 0
|
||||
// and outdoor athletes accumulate a few hours.
|
||||
TIME_IN_DAYLIGHT: "minutes",
|
||||
};
|
||||
|
||||
export function getUnitForType(type: string): string {
|
||||
@@ -114,6 +149,39 @@ const VALUE_RANGES: Record<string, { min: number; max: number }> = {
|
||||
VO2_MAX: { min: 5, max: 100 },
|
||||
// Body temperature °C — survivable lows ~28; severe hyperthermia ~45.
|
||||
BODY_TEMPERATURE: { min: 28, max: 45 },
|
||||
// ── v1.4.25 W5d Withings full coverage ──
|
||||
// Fat-free mass kg — adult plausibility, ~30 kg (small adult) to 120 kg
|
||||
// (large lean athlete). Same bounds as weight minus a fat-mass floor.
|
||||
FAT_FREE_MASS: { min: 10, max: 250 },
|
||||
// Fat mass kg — pairs with FAT_FREE_MASS so totals reconcile to weight.
|
||||
FAT_MASS: { min: 0, max: 250 },
|
||||
// Muscle mass kg — sub-component of fat-free mass; widest sensible bound.
|
||||
MUSCLE_MASS: { min: 5, max: 200 },
|
||||
// Skin temperature °C — surface temps run cooler than core. ScanWatch's
|
||||
// dermal sensor reports a relative offset that lands in the 25–40 °C
|
||||
// band; treat anything outside as a sensor glitch.
|
||||
SKIN_TEMPERATURE: { min: 20, max: 45 },
|
||||
// Pulse-wave velocity m/s — clinical ranges sit ~4–15 m/s. Higher
|
||||
// numbers indicate stiffer arteries (cardiovascular risk).
|
||||
PULSE_WAVE_VELOCITY: { min: 1, max: 30 },
|
||||
// Vascular age in years — Withings derives this from PWV + chronological
|
||||
// age; the value is a "biological age" not a chronological one. Hard cap
|
||||
// at 130 because that's the human longevity record.
|
||||
VASCULAR_AGE: { min: 10, max: 130 },
|
||||
// Visceral fat rating 1–12 (Withings' own scale; not a percent).
|
||||
VISCERAL_FAT: { min: 0, max: 30 },
|
||||
// ── v1.4.25 W8d Apple Health server-prep ──
|
||||
// Audio exposure dBA — Apple's "loud audio" warning sits at 80 dBA;
|
||||
// concerts run 100–115 dBA; 140 dBA is the pain threshold. The floor
|
||||
// of 30 dBA covers a quiet bedroom; anything below is silence and
|
||||
// almost certainly a sensor artefact.
|
||||
AUDIO_EXPOSURE_ENV: { min: 30, max: 140 },
|
||||
// Headphone audio caps slightly below the open-air upper edge because
|
||||
// sealed-driver listening physically cannot reach a concert PA's SPL.
|
||||
AUDIO_EXPOSURE_HEADPHONE: { min: 30, max: 140 },
|
||||
// Time in daylight (minutes/day) — full 24-hour window. Outdoor work
|
||||
// tops the range; sedentary indoor days sit near 0.
|
||||
TIME_IN_DAYLIGHT: { min: 0, max: 1440 },
|
||||
};
|
||||
|
||||
export function validateMeasurementRange(
|
||||
@@ -137,6 +205,14 @@ export const createMeasurementSchema = z
|
||||
// Only applies when type === BLOOD_GLUCOSE. Mirrored by a CHECK
|
||||
// constraint in Postgres (see migration 0021).
|
||||
glucoseContext: glucoseContextEnum.optional(),
|
||||
// v1.4.25 W10 reconcile (code-review M4): the single-entry POST
|
||||
// dropped `deviceType` silently because the column existed on
|
||||
// `Measurement` and was accepted by the batch route, but never
|
||||
// declared in this schema. iOS clients that POST one row at a
|
||||
// time (and dashboards that backfill manual rows with device
|
||||
// metadata) now persist the tag instead of seeing it disappear.
|
||||
// Accepts `null` so a client can explicitly clear the column.
|
||||
deviceType: z.string().min(1).max(32).nullable().optional(),
|
||||
})
|
||||
.refine((data) => validateMeasurementRange(data.type, data.value) === null, {
|
||||
message: "Value out of plausible range",
|
||||
|
||||
@@ -15,6 +15,18 @@ export const MEDICATION_CATEGORY_VALUES = [
|
||||
"OTHER",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* v1.4.25 W4d — Prisma-level treatment class. Orthogonal to
|
||||
* `MEDICATION_CATEGORY_VALUES` (the clinical taxonomy that lives in the
|
||||
* `medication_categories` side-table). GLP1 turns on the GLP-1
|
||||
* specialist surfaces — injection-site picker, titration history, pen
|
||||
* inventory, GLP-1-aware Coach replies. Future treatment classes drop
|
||||
* into this list (INSULIN, BIOLOGIC, FERTILITY, …).
|
||||
*/
|
||||
export const MEDICATION_TREATMENT_CLASS_VALUES = ["GENERIC", "GLP1"] as const;
|
||||
export type MedicationTreatmentClass =
|
||||
(typeof MEDICATION_TREATMENT_CLASS_VALUES)[number];
|
||||
|
||||
export const scheduleSchema = z.object({
|
||||
windowStart: z.string().regex(timeRegex, "Format: HH:mm"),
|
||||
windowEnd: z.string().regex(timeRegex, "Format: HH:mm"),
|
||||
@@ -28,6 +40,10 @@ export const createMedicationSchema = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
dose: z.string().min(1).max(50),
|
||||
category: z.enum(MEDICATION_CATEGORY_VALUES).optional(),
|
||||
/** v1.4.25 W4d — treatment-class discriminator (GENERIC | GLP1). */
|
||||
treatmentClass: z.enum(MEDICATION_TREATMENT_CLASS_VALUES).optional(),
|
||||
/** v1.4.25 W4d — doses per pen/vial for inventory tracking. */
|
||||
dosesPerUnit: z.number().int().min(1).max(100).optional(),
|
||||
schedules: z.array(scheduleSchema).min(1, "Mindestens ein Zeitfenster"),
|
||||
});
|
||||
|
||||
@@ -35,6 +51,8 @@ export const updateMedicationSchema = z.object({
|
||||
name: z.string().min(1).max(100).optional(),
|
||||
dose: z.string().min(1).max(50).optional(),
|
||||
category: z.enum(MEDICATION_CATEGORY_VALUES).optional(),
|
||||
treatmentClass: z.enum(MEDICATION_TREATMENT_CLASS_VALUES).optional(),
|
||||
dosesPerUnit: z.number().int().min(1).max(100).nullable().optional(),
|
||||
active: z.boolean().optional(),
|
||||
notificationsEnabled: z.boolean().optional(),
|
||||
schedules: z.array(scheduleSchema).optional(),
|
||||
@@ -86,6 +104,118 @@ export const updateIntakeEventSchema = z.object({
|
||||
.optional(),
|
||||
});
|
||||
|
||||
/**
|
||||
* v1.4.25 W19b — inventory (pen / vial) CRUD validators.
|
||||
*
|
||||
* The Prisma model carries a 4-state enum
|
||||
* (ACTIVE | IN_USE | EXPIRED | USED_UP); the API surface only lets
|
||||
* the user explicitly transition into IN_USE (mark-as-first-use) or
|
||||
* USED_UP (manual override). EXPIRED is owned by the daily cron and
|
||||
* the intake hook, so the PATCH schema deliberately omits it.
|
||||
*/
|
||||
export const createInventoryItemSchema = z.object({
|
||||
dosesTotal: z.number().int().min(1).max(100),
|
||||
printedExpiry: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.nullable()
|
||||
.optional(),
|
||||
purchasedAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.nullable()
|
||||
.optional(),
|
||||
notes: z.string().max(200).nullable().optional(),
|
||||
});
|
||||
|
||||
export const updateInventoryItemSchema = z.object({
|
||||
markAsFirstUseAt: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.optional(),
|
||||
markAsUsedUp: z.boolean().optional(),
|
||||
printedExpiry: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.nullable()
|
||||
.optional(),
|
||||
notes: z.string().max(200).nullable().optional(),
|
||||
});
|
||||
|
||||
export type CreateInventoryItemInput = z.infer<typeof createInventoryItemSchema>;
|
||||
export type UpdateInventoryItemInput = z.infer<typeof updateInventoryItemSchema>;
|
||||
|
||||
/**
|
||||
* v1.4.25 W21 Fix-K — `POST /api/medications/[id]/glp1` body validators.
|
||||
*
|
||||
* The convenience route accepts either a `doseChange` or an `inventory`
|
||||
* payload (the route picks one). Both branches were hand-rolled
|
||||
* `typeof === "number"` checks pre-Fix-K, which let `NaN`, `Infinity`,
|
||||
* negative doses, and unbounded notes slip through.
|
||||
*
|
||||
* Bounds:
|
||||
* - `doseValue` is finite, non-negative, capped at 100 mg (covers every
|
||||
* real-world GLP-1 step with headroom).
|
||||
* - `doseUnit` is a short string (mg / mcg / IE).
|
||||
* - `note` is capped at 500 characters so the field can't be used as a
|
||||
* blob smuggler.
|
||||
* - `effectiveFrom` is constrained to a ±5-year window around now —
|
||||
* a paper-record back-fill or a planned future step both fit, but
|
||||
* "1970" / "9999" do not.
|
||||
* - `delta` is a non-zero finite integer in [−100, 100] (the existing
|
||||
* inventory route caps `dosesTotal` at 100 doses per pen).
|
||||
* - `reason` is a bounded string (the route logs it; raw blob bad).
|
||||
*/
|
||||
const MAX_DOSE_MG = 100;
|
||||
const MAX_NOTE_CHARS = 500;
|
||||
const MAX_REASON_CHARS = 200;
|
||||
const MIN_EFFECTIVE_FROM = new Date("2020-01-01T00:00:00Z");
|
||||
const FIVE_YEARS_MS = 5 * 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export const glp1DoseChangePostSchema = z.object({
|
||||
effectiveFrom: z.iso
|
||||
.datetime({ offset: true })
|
||||
.transform((s) => new Date(s))
|
||||
.refine((d) => d.getTime() >= MIN_EFFECTIVE_FROM.getTime(), {
|
||||
message: "effectiveFrom must be on or after 2020-01-01",
|
||||
})
|
||||
.refine((d) => d.getTime() <= Date.now() + FIVE_YEARS_MS, {
|
||||
message: "effectiveFrom must be within 5 years of now",
|
||||
}),
|
||||
doseValue: z
|
||||
.number()
|
||||
.finite()
|
||||
.min(0)
|
||||
.max(MAX_DOSE_MG),
|
||||
doseUnit: z.string().min(1).max(10),
|
||||
note: z.string().max(MAX_NOTE_CHARS).nullable().optional(),
|
||||
});
|
||||
|
||||
export const glp1InventoryPostSchema = z.object({
|
||||
delta: z
|
||||
.number()
|
||||
.int()
|
||||
.finite()
|
||||
.min(-100)
|
||||
.max(100)
|
||||
.refine((n) => n !== 0, { message: "delta must be non-zero" }),
|
||||
reason: z.string().min(1).max(MAX_REASON_CHARS),
|
||||
});
|
||||
|
||||
export const glp1PostBodySchema = z
|
||||
.object({
|
||||
doseChange: glp1DoseChangePostSchema.optional(),
|
||||
inventory: glp1InventoryPostSchema.optional(),
|
||||
})
|
||||
.refine(
|
||||
(b) => Boolean(b.doseChange) !== Boolean(b.inventory),
|
||||
{ message: "Body must carry exactly one of doseChange or inventory" },
|
||||
);
|
||||
|
||||
export type Glp1DoseChangePostInput = z.infer<typeof glp1DoseChangePostSchema>;
|
||||
export type Glp1InventoryPostInput = z.infer<typeof glp1InventoryPostSchema>;
|
||||
export type Glp1PostBodyInput = z.infer<typeof glp1PostBodySchema>;
|
||||
|
||||
export type CreateMedicationInput = z.infer<typeof createMedicationSchema>;
|
||||
export type IntakeInput = z.infer<typeof intakeSchema>;
|
||||
export type ListIntakeEventsInput = z.infer<typeof listIntakeEventsSchema>;
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
/**
|
||||
* v1.4.25 W5e — per-user, per-metric-class source priority. When more
|
||||
* than one ingest source ships the same metric for the same day, the
|
||||
* analytics aggregator consults this map to pick ONE canonical source
|
||||
* per day (so cumulative metrics like steps don't double-count) or to
|
||||
* pick a "display preferred" source (for point measurements like weight
|
||||
* or BP — every source's row stays in the DB as an audit trail).
|
||||
*
|
||||
* Today (v1.4.25) only WITHINGS + MANUAL exist for any of these
|
||||
* metrics, so the function effectively no-ops for every user. The
|
||||
* shape lands now so v1.5's Apple Health passthrough drops onto a
|
||||
* known foundation without extra schema work.
|
||||
*
|
||||
* Persisted as `User.sourcePriorityJson` (nullable Jsonb). Null = use
|
||||
* `DEFAULT_SOURCE_PRIORITY` verbatim.
|
||||
*
|
||||
* v1.4.25 W8c — two-axis extension. The original (W5e) shape carried a
|
||||
* per-metric ladder at the top level (e.g. `weight: ["WITHINGS", …]`).
|
||||
* W8c adds two optional containers ON TOP of that:
|
||||
* - `metricPriority` — the per-metric ladder, identical in shape
|
||||
* to the top-level keys but nested. The
|
||||
* nested form is canonical going forward;
|
||||
* the flat form is kept as a backward-compat
|
||||
* shim (no migration / no UI for it).
|
||||
* - `deviceTypePriority` — within a source, which device wins. Keyed
|
||||
* by metric type with an optional `default`
|
||||
* ladder that covers metrics where the user
|
||||
* hasn't set a per-metric override.
|
||||
*
|
||||
* Both new keys are optional; existing rows with the flat shape keep
|
||||
* working unchanged. `parseSourcePriority()` merges everything onto
|
||||
* `DEFAULT_SOURCE_PRIORITY` plus an empty two-axis state so the call
|
||||
* site never has to think about which keys exist.
|
||||
*/
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import {
|
||||
measurementSourceEnum,
|
||||
measurementTypeEnum,
|
||||
} from "@/lib/validations/measurement";
|
||||
|
||||
// v1.4.25 Fix-G — `annotate` from `@/lib/logging/context` was the
|
||||
// canonical breadcrumb for a parse failure, but the helper pulls
|
||||
// `node:async_hooks` via `AsyncLocalStorage`. Any client component that
|
||||
// reaches for a type-only export here (e.g.
|
||||
// `src/components/settings/sources-section.tsx` importing
|
||||
// `DEFAULT_SOURCE_PRIORITY`) used to drag `node:async_hooks` into the
|
||||
// browser bundle and break the Turbopack build. The parser stays in the
|
||||
// shared module — splitting it out would ripple through every callsite —
|
||||
// so the breadcrumb path now goes through a runtime-resolved callback.
|
||||
// The server logging module registers the real `annotate` on first import
|
||||
// (via `registerSourcePriorityParseObserver`); the browser leaves it as
|
||||
// the no-op default and never traces `node:async_hooks`.
|
||||
type ParseFailureObserver = (entry: {
|
||||
meta: Record<string, unknown>;
|
||||
}) => void;
|
||||
let parseFailureObserver: ParseFailureObserver = () => {};
|
||||
|
||||
/**
|
||||
* Server-side opt-in for the parse-failure breadcrumb. Called once from
|
||||
* `@/lib/logging/context` so a buggy schema-tightening that silently
|
||||
* wipes a saved ladder still surfaces in ops dashboards. The client
|
||||
* bundle never imports the logging module, so the observer stays the
|
||||
* no-op default in the browser.
|
||||
*/
|
||||
export function registerSourcePriorityParseObserver(
|
||||
observer: ParseFailureObserver,
|
||||
): void {
|
||||
parseFailureObserver = observer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-type tag attached to a `Measurement` row. Mirrors
|
||||
* open-wearables (`watch | band | ring | phone | scale | other`) plus
|
||||
* an explicit `unknown` slot for legacy rows where the iOS app or
|
||||
* Withings webhook never told us which device produced the sample.
|
||||
*
|
||||
* Stored on `Measurement.deviceType` (nullable). NULL is treated as
|
||||
* `unknown` by `pickCanonicalSource()` — it falls through to the
|
||||
* source-only axis when no device-type override applies.
|
||||
*/
|
||||
export const deviceTypeEnum = z.enum([
|
||||
"watch",
|
||||
"band",
|
||||
"ring",
|
||||
"phone",
|
||||
"scale",
|
||||
"other",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
export type DeviceType = z.infer<typeof deviceTypeEnum>;
|
||||
|
||||
/**
|
||||
* Per-metric source ladder. Same shape as the v1.4.25 W5e top-level
|
||||
* keys; lifted into a nested object so the schema has room for the new
|
||||
* `deviceTypePriority` sibling without clobbering the metric keys.
|
||||
*
|
||||
* The 8-entry cap is a sanity bound (we have 4 sources today, the cap
|
||||
* leaves headroom without inviting a megabyte-blob payload).
|
||||
*/
|
||||
const metricSourceLadder = z.array(measurementSourceEnum).max(8);
|
||||
|
||||
const metricPriorityObjectSchema = z
|
||||
.object({
|
||||
// ── Cumulative metrics — sum-per-day; pick ONE source per day. ──
|
||||
steps: metricSourceLadder,
|
||||
activeEnergy: metricSourceLadder,
|
||||
walkingRunningDistance: metricSourceLadder,
|
||||
flightsClimbed: metricSourceLadder,
|
||||
// ── Sleep — pick best-resolution source per night. ──
|
||||
sleep: metricSourceLadder,
|
||||
// ── Point measurements — all sources kept; this controls
|
||||
// "display preference" when multiple sources happen to capture
|
||||
// the same metric on the same day.
|
||||
weight: metricSourceLadder,
|
||||
bloodPressure: metricSourceLadder,
|
||||
pulse: metricSourceLadder,
|
||||
bodyFat: metricSourceLadder,
|
||||
bodyTemperature: metricSourceLadder,
|
||||
spo2: metricSourceLadder,
|
||||
hrv: metricSourceLadder,
|
||||
restingHeartRate: metricSourceLadder,
|
||||
vo2Max: metricSourceLadder,
|
||||
})
|
||||
.partial();
|
||||
|
||||
/**
|
||||
* v1.4.25 W8c — device-type ladder per metric class. Walked by
|
||||
* `pickCanonicalSource()` AFTER the source axis has narrowed the
|
||||
* candidate row down to the winning source.
|
||||
*
|
||||
* Two-level lookup:
|
||||
* - `deviceTypePriority[metric]` — per-metric override (wins).
|
||||
* - `deviceTypePriority.default` — global fallback (used when the
|
||||
* metric has no per-key entry).
|
||||
*
|
||||
* Cap mirrors the source ladder (8 entries) and is generous; the enum
|
||||
* itself has 7 slots.
|
||||
*/
|
||||
const deviceTypeLadder = z.array(deviceTypeEnum).max(8);
|
||||
|
||||
const deviceTypePrioritySchema = z
|
||||
.object({
|
||||
// Global fallback applied when no per-metric override exists.
|
||||
default: deviceTypeLadder,
|
||||
// Per-metric overrides — keyed by MeasurementType enum value so
|
||||
// iOS-emitted device-type tags survive a future per-metric tweak
|
||||
// without schema churn.
|
||||
})
|
||||
.catchall(deviceTypeLadder)
|
||||
// `partial()` so callers can supply only `default`, only an override,
|
||||
// or omit the key entirely.
|
||||
.partial();
|
||||
|
||||
/**
|
||||
* Top-level schema. Flat metric keys (W5e shape) sit alongside the new
|
||||
* `metricPriority` + `deviceTypePriority` containers. The flat shape is
|
||||
* a backward-compat alias — when both exist, `metricPriority` wins.
|
||||
*/
|
||||
export const sourcePrioritySchema = z
|
||||
.object({
|
||||
// ── v1.4.25 W5e flat shape (backward-compat) ──
|
||||
steps: metricSourceLadder,
|
||||
activeEnergy: metricSourceLadder,
|
||||
walkingRunningDistance: metricSourceLadder,
|
||||
flightsClimbed: metricSourceLadder,
|
||||
sleep: metricSourceLadder,
|
||||
weight: metricSourceLadder,
|
||||
bloodPressure: metricSourceLadder,
|
||||
pulse: metricSourceLadder,
|
||||
bodyFat: metricSourceLadder,
|
||||
bodyTemperature: metricSourceLadder,
|
||||
spo2: metricSourceLadder,
|
||||
hrv: metricSourceLadder,
|
||||
restingHeartRate: metricSourceLadder,
|
||||
vo2Max: metricSourceLadder,
|
||||
// ── v1.4.25 W8c additions ──
|
||||
metricPriority: metricPriorityObjectSchema,
|
||||
deviceTypePriority: deviceTypePrioritySchema,
|
||||
})
|
||||
.partial();
|
||||
|
||||
export type SourcePriority = z.infer<typeof sourcePrioritySchema>;
|
||||
export type MetricPriority = z.infer<typeof metricPriorityObjectSchema>;
|
||||
export type DeviceTypePriority = z.infer<typeof deviceTypePrioritySchema>;
|
||||
|
||||
/**
|
||||
* Metric-class keys carried by `SourcePriority`. Listed once here so
|
||||
* the Settings UI, the aggregator helper, and the tests all read from
|
||||
* the same place — a future addition (Apple Health workouts in v1.5)
|
||||
* shows up everywhere by extending one constant.
|
||||
*/
|
||||
export const SOURCE_PRIORITY_METRIC_KEYS = [
|
||||
"steps",
|
||||
"activeEnergy",
|
||||
"walkingRunningDistance",
|
||||
"flightsClimbed",
|
||||
"sleep",
|
||||
"weight",
|
||||
"bloodPressure",
|
||||
"pulse",
|
||||
"bodyFat",
|
||||
"bodyTemperature",
|
||||
"spo2",
|
||||
"hrv",
|
||||
"restingHeartRate",
|
||||
"vo2Max",
|
||||
] as const;
|
||||
|
||||
export type SourcePriorityMetricKey =
|
||||
(typeof SOURCE_PRIORITY_METRIC_KEYS)[number];
|
||||
|
||||
/**
|
||||
* Marc-directive 2026-05-14 defaults:
|
||||
* - Cumulative metrics (steps, activeEnergy, walkingRunningDistance,
|
||||
* flightsClimbed): APPLE_HEALTH > WITHINGS > MANUAL. iOS HealthKit
|
||||
* aggregates ScanWatch + iPhone sensors into a single canonical
|
||||
* stream, so when the iOS passthrough lands in v1.5 it's the most
|
||||
* complete source for cumulative metrics.
|
||||
* - Sleep + HRV + RHR: APPLE_HEALTH > WITHINGS. HealthKit has higher
|
||||
* resolution (per-minute samples) than Withings' nightly summary.
|
||||
* - Point measurements (weight, BP, pulse, body-fat, body-temp,
|
||||
* SpO2, VO2 max): WITHINGS > APPLE_HEALTH > MANUAL. Withings
|
||||
* devices are the primary sensor (scale, BPM cuff, ScanWatch
|
||||
* pulse-ox, Thermo). Apple Health is second-hand (HealthKit
|
||||
* receives the same reading via Withings' Health Mate iOS app).
|
||||
*/
|
||||
export const DEFAULT_SOURCE_PRIORITY: Required<MetricPriority> = {
|
||||
steps: ["APPLE_HEALTH", "WITHINGS", "MANUAL"],
|
||||
activeEnergy: ["APPLE_HEALTH", "WITHINGS", "MANUAL"],
|
||||
walkingRunningDistance: ["APPLE_HEALTH", "WITHINGS", "MANUAL"],
|
||||
flightsClimbed: ["APPLE_HEALTH", "WITHINGS", "MANUAL"],
|
||||
sleep: ["APPLE_HEALTH", "WITHINGS"],
|
||||
hrv: ["APPLE_HEALTH", "WITHINGS"],
|
||||
restingHeartRate: ["APPLE_HEALTH", "WITHINGS"],
|
||||
weight: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
bloodPressure: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
pulse: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
bodyFat: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
bodyTemperature: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
spo2: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
vo2Max: ["WITHINGS", "APPLE_HEALTH", "MANUAL"],
|
||||
};
|
||||
|
||||
/**
|
||||
* v1.4.25 W8c — default device-type ladder. Open-wearables' research
|
||||
* recommendation: watch first (highest fidelity for cumulative + HR
|
||||
* metrics), then ring/band (wrist-adjacent), then phone (fallback
|
||||
* cumulative when wearables are off-wrist), then scale (only writes
|
||||
* weight/body comp anyway), then catch-all `other` / `unknown`.
|
||||
*
|
||||
* Note: the picker treats a row with `deviceType = null` as `unknown`
|
||||
* — legacy Withings rows (pre-v1.4.25 W8c) fall to the bottom of the
|
||||
* ladder but never get filtered out, because the source-axis pick
|
||||
* already narrowed to one source.
|
||||
*/
|
||||
export const DEFAULT_DEVICE_TYPE_PRIORITY: readonly DeviceType[] = [
|
||||
"watch",
|
||||
"ring",
|
||||
"band",
|
||||
"phone",
|
||||
"scale",
|
||||
"other",
|
||||
"unknown",
|
||||
];
|
||||
|
||||
/**
|
||||
* Fully-resolved shape returned by `parseSourcePriority`. The flat
|
||||
* per-metric ladder is always populated (defaulted); the two-axis
|
||||
* containers default to empty objects so call sites can read
|
||||
* `resolved.metricPriority.weight` etc. without an `undefined` guard.
|
||||
*/
|
||||
export interface ResolvedSourcePriority extends Required<MetricPriority> {
|
||||
/**
|
||||
* Canonical per-metric ladder. Merged from `metricPriority` (W8c
|
||||
* nested shape) over the flat top-level keys (W5e shape) over
|
||||
* `DEFAULT_SOURCE_PRIORITY`. Always populated for every metric.
|
||||
*/
|
||||
metricPriority: Required<MetricPriority>;
|
||||
/**
|
||||
* Per-metric device-type override + a global fallback ladder. Both
|
||||
* keys default to the empty state (no overrides) so the picker uses
|
||||
* `DEFAULT_DEVICE_TYPE_PRIORITY` as the implicit fallback.
|
||||
*/
|
||||
deviceTypePriority: DeviceTypePriority;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the persisted Json blob into a fully-defaulted priority map.
|
||||
* Missing keys fall back to `DEFAULT_SOURCE_PRIORITY` — the UI never
|
||||
* has to think about which keys exist, and a future schema addition
|
||||
* (a new metric class) carries its default automatically until the
|
||||
* user edits the field.
|
||||
*
|
||||
* Merge order (high → low):
|
||||
* 1. `raw.metricPriority` (W8c nested shape; canonical going forward)
|
||||
* 2. `raw` top-level flat keys (W5e backward-compat)
|
||||
* 3. `DEFAULT_SOURCE_PRIORITY`
|
||||
*/
|
||||
export function parseSourcePriority(raw: unknown): ResolvedSourcePriority {
|
||||
if (raw == null) return buildResolved({}, {}, {});
|
||||
|
||||
const parsed = sourcePrioritySchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
// v1.4.25 W10 reconcile (Sr-M2) — emit a wide-event tag so a future
|
||||
// schema-tightening regression that silently nukes a user's saved
|
||||
// ladder surfaces in ops dashboards rather than as a "why did my
|
||||
// priorities reset?" user report. `annotate()` is a no-op outside a
|
||||
// request context, so the static settings-page render and tests
|
||||
// remain side-effect-free.
|
||||
parseFailureObserver({
|
||||
meta: {
|
||||
sourcePriority: {
|
||||
parse: "failed",
|
||||
issueCount: parsed.error.issues.length,
|
||||
firstIssuePath: parsed.error.issues[0]?.path.join(".") ?? null,
|
||||
},
|
||||
},
|
||||
});
|
||||
return buildResolved({}, {}, {});
|
||||
}
|
||||
|
||||
// Pull the W5e flat per-metric ladder off the top level. Drop the
|
||||
// two W8c container keys so the rest of the object is just the flat
|
||||
// metric ladder we can spread without TS complaining.
|
||||
const {
|
||||
metricPriority: nested,
|
||||
deviceTypePriority,
|
||||
...flatMetricLadder
|
||||
} = parsed.data;
|
||||
return buildResolved(flatMetricLadder, nested ?? {}, deviceTypePriority ?? {});
|
||||
}
|
||||
|
||||
function buildResolved(
|
||||
flat: Partial<MetricPriority>,
|
||||
nested: Partial<MetricPriority>,
|
||||
deviceTypePriority: DeviceTypePriority,
|
||||
): ResolvedSourcePriority {
|
||||
// Merge: defaults < flat (W5e) < nested (W8c).
|
||||
const merged: Required<MetricPriority> = {
|
||||
...DEFAULT_SOURCE_PRIORITY,
|
||||
...flat,
|
||||
...nested,
|
||||
};
|
||||
const resolved: ResolvedSourcePriority = {
|
||||
...merged,
|
||||
metricPriority: merged,
|
||||
deviceTypePriority,
|
||||
};
|
||||
// v1.4.25 W10 reconcile (Code-M1) — deep-freeze the resolved blob so
|
||||
// a caller who mutates `resolved.metricPriority.weight = …` after
|
||||
// parseSourcePriority() returns trips at runtime instead of silently
|
||||
// desyncing the two views (the top-level flat keys share their
|
||||
// backing object with `metricPriority` via the spread above, but
|
||||
// anything written through the alias post-freeze raises in strict
|
||||
// mode and surfaces in dev). Freezing the leaves keeps the contract
|
||||
// immutable end-to-end without copying the source ladders.
|
||||
for (const ladder of Object.values(merged)) {
|
||||
Object.freeze(ladder);
|
||||
}
|
||||
for (const ladder of Object.values(deviceTypePriority)) {
|
||||
if (ladder) Object.freeze(ladder);
|
||||
}
|
||||
Object.freeze(merged);
|
||||
Object.freeze(deviceTypePriority);
|
||||
Object.freeze(resolved);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.25 W8c — runtime device-type checker for ingest paths. Returns
|
||||
* a `DeviceType` for any input the iOS app or Withings webhook might
|
||||
* supply; falls back to `"unknown"` when the value isn't part of the
|
||||
* canonical enum. Keeps the picker on the happy path even when a
|
||||
* legacy row has `deviceType = null` or a typoed value.
|
||||
*/
|
||||
export function normalizeDeviceType(raw: unknown): DeviceType {
|
||||
const parsed = deviceTypeEnum.safeParse(raw);
|
||||
return parsed.success ? parsed.data : "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: walk the metric-key list and return the source ladder
|
||||
* for one metric. Centralised so the picker, the UI, and tests share
|
||||
* one path; future axis additions slot in here.
|
||||
*/
|
||||
export function getSourceLadder(
|
||||
resolved: ResolvedSourcePriority,
|
||||
metricKey: SourcePriorityMetricKey,
|
||||
): readonly z.infer<typeof measurementSourceEnum>[] {
|
||||
return resolved.metricPriority[metricKey];
|
||||
}
|
||||
|
||||
/**
|
||||
* v1.4.25 W8c — resolve the device-type ladder for a given metric.
|
||||
* Lookup order:
|
||||
* 1. `deviceTypePriority[metricType]` — per-metric override.
|
||||
* 2. `deviceTypePriority.default` — global fallback the user set.
|
||||
* 3. `DEFAULT_DEVICE_TYPE_PRIORITY` — the constant ladder.
|
||||
*
|
||||
* The metric key is a `MeasurementType` enum value (e.g. `"WEIGHT"`),
|
||||
* not the `SourcePriorityMetricKey` (e.g. `"weight"`), because the
|
||||
* iOS-emitted `deviceType` field on `Measurement` is tagged per
|
||||
* `MeasurementType` row, not per `SourcePriorityMetricKey` aggregation
|
||||
* bucket. The Settings UI translates between the two.
|
||||
*/
|
||||
export function getDeviceTypeLadder(
|
||||
resolved: ResolvedSourcePriority,
|
||||
metricType: z.infer<typeof measurementTypeEnum> | string,
|
||||
): readonly DeviceType[] {
|
||||
const override = resolved.deviceTypePriority[metricType];
|
||||
if (override && override.length > 0) return override;
|
||||
const fallback = resolved.deviceTypePriority.default;
|
||||
if (fallback && fallback.length > 0) return fallback;
|
||||
return DEFAULT_DEVICE_TYPE_PRIORITY;
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { z } from "zod/v4";
|
||||
import { measurementSourceEnum } from "./measurement";
|
||||
|
||||
/**
|
||||
* Workout sport-type union.
|
||||
*
|
||||
* Stored as a TEXT column at the DB layer (see `Workout.sport_type` in
|
||||
* `prisma/schema.prisma`) rather than a Postgres enum. Apple alone has
|
||||
* 70+ `HKWorkoutActivityType` values and the long tail (paddle / row /
|
||||
* ski / etc.) only grows release-on-release. A Zod `enum` here gives
|
||||
* compile-time exhaustiveness without making every new sport a Postgres
|
||||
* migration. Adding a new sport: append the literal to this union and
|
||||
* any source-specific code that maps to it (e.g. an HK numeric-code →
|
||||
* union entry in `apple-health-mapping.ts`).
|
||||
*
|
||||
* The initial roster covers ≥98% of typical workouts observed across
|
||||
* the open-source Apple Health corpora referenced in the W8d research
|
||||
* outline. Anything not in the list lands as `"other"` until promoted
|
||||
* to a first-class member.
|
||||
*/
|
||||
export const workoutSportTypeEnum = z.enum([
|
||||
"walking",
|
||||
"running",
|
||||
"cycling",
|
||||
"hiking",
|
||||
"swimming",
|
||||
"rowing",
|
||||
"elliptical",
|
||||
"stairClimber",
|
||||
"yoga",
|
||||
"mindAndBody",
|
||||
"strength",
|
||||
"hiit",
|
||||
"dance",
|
||||
"golf",
|
||||
"tennis",
|
||||
"basketball",
|
||||
"soccer",
|
||||
"crossTraining",
|
||||
"mixedCardio",
|
||||
"other",
|
||||
]);
|
||||
|
||||
export type WorkoutSportType = z.infer<typeof workoutSportTypeEnum>;
|
||||
|
||||
/**
|
||||
* Upper bound on points per route LineString. A 24h ultra at 1Hz lands
|
||||
* at 86 400 points; 20 000 covers any normal run / ride / hike while
|
||||
* still rejecting pathological payloads (an attacker shipping a 5 MB
|
||||
* route per workout * 100 workouts/batch * unbounded retries). The
|
||||
* route geometry is the largest tail in the batch payload — keeping it
|
||||
* bounded keeps the total request body bounded with it.
|
||||
*/
|
||||
export const MAX_ROUTE_POINTS = 20_000;
|
||||
|
||||
/**
|
||||
* GeoJSON LineString — the WorkoutRoute.geometry shape. RFC 7946 §3.1.4
|
||||
* with one HealthLog-specific allowance: the altitude component on
|
||||
* each coordinate is optional. Apple HKWorkoutRoute carries it; some
|
||||
* GPX imports do not.
|
||||
*/
|
||||
export const geoJsonLineStringSchema = z.object({
|
||||
type: z.literal("LineString"),
|
||||
coordinates: z
|
||||
.array(
|
||||
z
|
||||
.tuple([z.number().min(-180).max(180), z.number().min(-90).max(90)])
|
||||
.rest(z.number()),
|
||||
)
|
||||
.min(2, "LineString requires at least 2 points")
|
||||
.max(
|
||||
MAX_ROUTE_POINTS,
|
||||
`LineString exceeds the ${MAX_ROUTE_POINTS}-point cap`,
|
||||
),
|
||||
});
|
||||
|
||||
export type GeoJsonLineString = z.infer<typeof geoJsonLineStringSchema>;
|
||||
|
||||
/**
|
||||
* Per-sample timestamp + speed companion to the LineString. Parallel
|
||||
* to `coordinates` — same length, one entry per point. NULL at the
|
||||
* column level when the source only ships static GPX (Withings).
|
||||
*/
|
||||
export const workoutRouteSamplesSchema = z.array(
|
||||
z.object({
|
||||
t: z.iso.datetime({ offset: true }),
|
||||
speedMs: z.number().min(0).max(50).optional(),
|
||||
hr: z.number().int().min(20).max(300).optional(),
|
||||
}),
|
||||
);
|
||||
|
||||
export type WorkoutRouteSamples = z.infer<typeof workoutRouteSamplesSchema>;
|
||||
|
||||
/**
|
||||
* Workout insert payload — the shape `POST /api/workouts/batch` accepts.
|
||||
* Defined here so the iOS Swift session can generate its DTO against the
|
||||
* locked contract and the v1.4.26 XML import worker has the same target.
|
||||
*
|
||||
* Cross-field invariants enforced via `.superRefine()`:
|
||||
* - `endedAt` MUST be strictly greater than `startedAt`. A workout
|
||||
* with `endedAt <= startedAt` produces a non-positive
|
||||
* `durationSec`, which downstream consumers (PR detector, weekly
|
||||
* report, dashboards) treat as a "real" zero — locking in a
|
||||
* fastest-5km time of zero seconds is far worse than refusing the
|
||||
* ingest at the schema gate.
|
||||
* - When `route.sampleTimestamps` is present, its length MUST equal
|
||||
* `route.geometry.coordinates.length`. A desynced pair silently
|
||||
* degrades downstream analytics (per-sample HR / speed would line
|
||||
* up against the wrong coordinate), so we hard-fail at parse time.
|
||||
*/
|
||||
export const createWorkoutSchema = z
|
||||
.object({
|
||||
sportType: workoutSportTypeEnum,
|
||||
startedAt: z.iso.datetime({ offset: true }).transform((s) => new Date(s)),
|
||||
endedAt: z.iso.datetime({ offset: true }).transform((s) => new Date(s)),
|
||||
totalEnergyKcal: z.number().min(0).max(50000).optional(),
|
||||
totalDistanceM: z.number().min(0).max(1_000_000).optional(),
|
||||
avgHeartRate: z.number().int().min(20).max(300).optional(),
|
||||
maxHeartRate: z.number().int().min(20).max(300).optional(),
|
||||
minHeartRate: z.number().int().min(20).max(300).optional(),
|
||||
stepCount: z.number().int().min(0).max(200_000).optional(),
|
||||
elevationM: z.number().min(-500).max(10_000).optional(),
|
||||
pauseDurationSec: z.number().int().min(0).max(86_400).optional(),
|
||||
source: measurementSourceEnum.optional().default("MANUAL"),
|
||||
externalId: z.string().max(128).optional(),
|
||||
externalSourceVersion: z.string().max(64).optional(),
|
||||
metadata: z.record(z.string(), z.unknown()).optional(),
|
||||
route: z
|
||||
.object({
|
||||
geometry: geoJsonLineStringSchema,
|
||||
sampleTimestamps: workoutRouteSamplesSchema.optional(),
|
||||
})
|
||||
.optional(),
|
||||
})
|
||||
.superRefine((value, ctx) => {
|
||||
if (value.endedAt.getTime() <= value.startedAt.getTime()) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["endedAt"],
|
||||
message: "endedAt must be strictly after startedAt",
|
||||
});
|
||||
}
|
||||
const samples = value.route?.sampleTimestamps;
|
||||
const coords = value.route?.geometry.coordinates;
|
||||
if (samples && coords && samples.length !== coords.length) {
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
path: ["route", "sampleTimestamps"],
|
||||
message:
|
||||
"sampleTimestamps length must match geometry.coordinates length",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type CreateWorkoutInput = z.infer<typeof createWorkoutSchema>;
|
||||
|
||||
/**
|
||||
* Upper bound on workouts per batch ingest call. Workouts are heavier
|
||||
* than measurements (each may carry a 20 000-point route geometry), so
|
||||
* the cap is an order of magnitude tighter than the 500-entry
|
||||
* measurements batch. A cold-start iOS HealthKit backfill is "every
|
||||
* workout I've ever recorded" — 100 covers a healthy multi-year history
|
||||
* and rejects pathological cases without forcing pagination on the
|
||||
* happy path.
|
||||
*/
|
||||
export const MAX_WORKOUTS_PER_BATCH = 100;
|
||||
|
||||
/**
|
||||
* Batch ingest payload — `{ workouts: [createWorkoutSchema, ...] }`.
|
||||
* Mirrors `createBatchMeasurementSchema` shape so the iOS sync engine
|
||||
* can re-use the same retry / cursor plumbing. Each entry is a typed
|
||||
* workout; an optional nested `route` carries the GeoJSON LineString.
|
||||
*/
|
||||
export const createBatchWorkoutSchema = z.object({
|
||||
workouts: z
|
||||
.array(createWorkoutSchema)
|
||||
.min(1)
|
||||
.max(MAX_WORKOUTS_PER_BATCH),
|
||||
});
|
||||
|
||||
export type CreateBatchWorkoutInput = z.infer<typeof createBatchWorkoutSchema>;
|
||||
Reference in new issue
Block a user