Merge the environment and ingest route group

This commit is contained in:
Marc-André Bombeck committed 2026-08-22 13:28:18 +02:00
commit c985f634aa
44 files changed
+3943 -242

No files matched your search

+117
View File
@@ -0,0 +1,117 @@
/**
* Request schemas for the AI-provider surfaces: the configuration write
* (`PATCH /api/user/ai-provider`) and the connection probe
* (`POST /api/ai/test`).
*
* They live outside the route files so the OpenAPI registry can import them (a
* route module may only export handlers plus the Next.js route config), which
* keeps the published contract and the runtime parser one object.
*
* Both bodies carry plaintext credentials, which puts one constraint on every
* rule below: a validation message must never interpolate the value it
* rejected. Zod's built-in type, enum and range messages name the received
* TYPE and never the received value, so the multi-issue 422 these feed is safe
* to return. A `.refine()` with a message that quotes its input would break
* that, and would put a key in an error body.
*/
import { z } from "zod/v4";
/** The five provider kinds a user may select. */
export const AI_PROVIDER_KINDS = [
"OPENAI",
"ANTHROPIC",
"LOCAL",
"OPENAI_COMPATIBLE",
"CHATGPT_OAUTH",
] as const;
export const aiProviderKindSchema = z.enum(AI_PROVIDER_KINDS);
/**
* A field the caller may set, clear, or leave alone.
*
* Three states, and the difference matters on every column here: an OMITTED
* key leaves the stored value untouched, `null` or `""` clears it, and a
* non-empty string replaces it. The empty string is not a synonym for "no
* change" anywhere on this surface — the settings forms send `null` and `""`
* interchangeably to mean "clear", and both have always cleared.
*/
const clearableString = z.string().nullable();
/**
* `PATCH /api/user/ai-provider` — a partial update of the provider config.
*
* The route used to inspect the body key by key with `typeof` guards, which
* meant a wrongly-typed value (a numeric `model`, a boolean `baseUrl`) was
* SKIPPED rather than refused: the write went ahead without it, and a body of
* nothing but such keys came back as "No valid fields" without naming one.
* This schema is what closes that — every accepted field now states its type,
* and a mismatch is a named issue in the standard multi-issue 422.
*
* The accepted field set is exactly what the route already accepted; this
* describes the existing contract rather than changing it. In particular the
* object is deliberately NOT `.strict()`: an unrecognised key has always been
* ignored here, and refusing one now would break a client sending a field this
* server does not know yet. Unknown keys are dropped, as before.
*/
export const aiProviderPatchSchema = z.object({
/**
* The selected provider. `null` / `""` clears it. Unlike every other field
* this one has always REFUSED an unrecognised value rather than skipping it,
* and still does.
*/
provider: z
.union([aiProviderKindSchema, z.literal("")])
.nullable()
.optional(),
/** Trimmed on write; whitespace-only clears, like `""`. */
model: clearableString.optional(),
/**
* Custom base URL for the LOCAL provider. Trimmed, then run through the
* SSRF floor at the route — a private host is refused there, not here,
* because the allowlist is operator state rather than a shape rule.
*/
baseUrl: clearableString.optional(),
/** The OpenAI-compatible gateway's own base URL. Same SSRF floor. */
compatBaseUrl: clearableString.optional(),
compatModel: clearableString.optional(),
/** Encrypted at rest on write; never echoed back by the read. */
compatKey: clearableString.optional(),
anthropicKey: clearableString.optional(),
localKey: clearableString.optional(),
openaiKey: clearableString.optional(),
/**
* Per-user AI response timeout in seconds. `null` restores the built-in
* default. The 10 s floor is below what any real backend beats and the
* 600 s ceiling is generous for a slow self-hosted one; outside that range
* the value is refused rather than clamped, so a typo is visible.
*/
responseTimeoutSeconds: z
.number()
.int()
.min(10, "Response timeout must be between 10 and 600 seconds")
.max(600, "Response timeout must be between 10 and 600 seconds")
.nullable()
.optional(),
});
export type AiProviderPatchInput = z.infer<typeof aiProviderPatchSchema>;
export const aiTestOverrideSchema = z
.object({
provider: aiProviderKindSchema.optional().nullable(),
model: z.string().min(1).max(120).optional().nullable(),
baseUrl: z.string().url().max(2048).optional().nullable(),
anthropicKey: z.string().min(1).max(500).optional().nullable(),
localKey: z.string().min(1).max(500).optional().nullable(),
openaiKey: z.string().min(1).max(500).optional().nullable(),
// The OpenAI-compatible gateway's own fields, kept separate from
// `baseUrl` / `openaiKey` so testing an unsaved gateway config can never
// reach the pinned OpenAI arm and vice versa.
compatBaseUrl: z.string().url().max(2048).optional().nullable(),
compatKey: z.string().min(1).max(500).optional().nullable(),
compatModel: z.string().min(1).max(120).optional().nullable(),
})
.strict();
export type AiTestOverrideInput = z.infer<typeof aiTestOverrideSchema>;
+29
View File
@@ -0,0 +1,29 @@
/**
* Query validation for `GET /api/analytics`.
*
* One parameter, one legal value, and the point of writing it down is that
* the route used to compare the raw string against `"summaries"` and fall
* through to the thick default body on anything else. `?slice=summary` then
* ran the whole 30-query chain and answered as if nothing were wrong, which
* is the most expensive way this surface can absorb a typo.
*
* Lives outside the route file so the OpenAPI registry can import it (a route
* module may only export handlers plus the Next.js route config).
*/
import { z } from "zod/v4";
/** The slices `GET /api/analytics` knows how to serve. */
export const ANALYTICS_SLICES = ["summaries"] as const;
export const analyticsSliceEnum = z.enum(ANALYTICS_SLICES);
export const analyticsQuerySchema = z.object({
/**
* `summaries` selects the slim tile-strip body. Omitted selects the thick
* default body. Any other value is refused — falling through to the
* default would hide the typo behind the more expensive read.
*/
slice: analyticsSliceEnum.optional(),
});
export type AnalyticsQuery = z.infer<typeof analyticsQuerySchema>;
+104
View File
@@ -264,6 +264,55 @@ const reminderPhaseConfigSchema = z
})
.passthrough();
/**
* One archived schedule era.
*
* `supersededByIndex` is the self-reference, and it is a POSITION in the
* drug's own `scheduleRevisions` array rather than an id: a portable restore
* mints fresh ids, so an id would address nothing. It stays a plain integer
* with no range check here on purpose — the file is the wrong place to learn
* that a position is out of range, because the array it indexes into is the
* array being parsed. The restore does that check, against the rows it
* actually wrote, and reports what it cannot resolve.
*
* `payload` is the snapshot of the superseded schedule rows, carried as
* written. Unknown on purpose rather than typed: it is an era's frozen copy of
* a shape that has changed several times, and a restore must not refuse a file
* because a five-release-old snapshot spells a field the current form does not.
*/
const medicationScheduleRevisionSchema = z
.object({
id: z.string().min(1).optional(),
validFrom: isoDateTime,
validUntil: isoDateTime,
payload: z.unknown(),
source: z.string().min(1).optional(),
supersededByIndex: z.number().int().nullable().optional(),
createdAt: isoDateTime.optional(),
})
.passthrough();
/**
* What a medication was supposed to move.
*
* The lab arm is a biomarker NAME rather than an id, the way a lab result's
* cross-reference is: the id is fresh on a portable restore, and `Biomarker`
* is unique on `(userId, name)`. Both arms are nullable because the live
* schema produces a row with neither — deleting a biomarker sets the column
* NULL and leaves the override behind as an orphan the resolver reads as "no
* override".
*/
const medicationEfficacyTargetSchema = z
.object({
id: z.string().min(1).optional(),
measurementType: z.enum(MeasurementType).nullable().optional(),
biomarkerName: z.string().min(1).nullable().optional(),
primary: z.boolean().optional(),
createdAt: isoDateTime.optional(),
updatedAt: isoDateTime.optional(),
})
.passthrough();
const medicationSchema = z
.object({
id: z.string().min(1).optional(),
@@ -307,6 +356,12 @@ const medicationSchema = z
inventoryItems: z.array(medicationInventoryItemSchema).default([]),
inventoryEvents: z.array(medicationInventoryEventSchema).default([]),
phaseConfig: reminderPhaseConfigSchema.nullable().optional(),
// Same default, same reason: an older file parses, and a drug whose
// target the resolver derives rather than the person pinning it writes [].
efficacyTargets: z.array(medicationEfficacyTargetSchema).default([]),
// Same default again. A drug whose plan has never been replaced has no
// archived era, and a file written before the eras travelled has no key.
scheduleRevisions: z.array(medicationScheduleRevisionSchema).default([]),
})
.passthrough();
@@ -1514,6 +1569,36 @@ const documentBackupSchema = z
})
.passthrough();
/**
* One ECG strip.
*
* `waveformEncrypted` and `waveform` are the two ends of the same contract, so
* both are optional here and exactly one arrives: a disaster-recovery file
* carries the ciphertext, a portable file carries the micro-volt samples.
* Requiring either would refuse half the valid files. `samplingFrequency` and
* `sampleCount` stay required in both, because without them the samples are a
* list of numbers with no time axis.
*/
const ecgRecordingBackupSchema = z
.object({
id: z.string().min(1).optional(),
source: z.enum(MeasurementSource),
externalRecordingId: z.string().min(1),
recordedAt: isoDateTime,
waveformEncrypted: base64BytesSchema.optional(),
waveform: z.array(z.number()).optional(),
samplingFrequency: z.number().int(),
sampleCount: z.number().int(),
durationSeconds: z.number().nullable().optional(),
lead: z.string().nullable().optional(),
averageHeartRate: z.number().int().nullable().optional(),
rhythmClassification: z.enum(RhythmClassification).nullable().optional(),
measurementId: z.string().min(1).nullable().optional(),
createdAt: isoDateTime,
updatedAt: isoDateTime,
})
.passthrough();
const backupManifestSchema = z
.object({
documents: z
@@ -1627,6 +1712,10 @@ export const backupPayloadSchema = z
environmentTravelLocations: z
.array(environmentTravelLocationBackupSchema)
.default([]),
// The ECG strips. Defaulted for the same reason as the sections above: a
// file written before the recordings travelled carries no key, and an
// account whose watch has never taken one writes [].
ecgRecordings: z.array(ecgRecordingBackupSchema).default([]),
manifest: backupManifestSchema.nullable().default(null),
// v1.37.19 (A6-9) — field paths a PORTABLE export could not decrypt
// (fail-soft nulls). Disclosed in the file so a nulled field is
@@ -1663,6 +1752,10 @@ export interface BackupSummary {
intakeEvents: number;
/** Side effects recorded against a drug, across every medication. */
medicationSideEffects: number;
/** Pinned efficacy targets, across every medication. */
medicationEfficacyTargets: number;
/** Archived schedule eras, across every medication. */
medicationScheduleRevisions: number;
moodEntries: number;
/** v1.15.0 — observed cycle spans in the backup. */
cycles: number;
@@ -1737,6 +1830,8 @@ export interface BackupSummary {
environmentContexts: number;
/** Declared stretches spent away from home. */
environmentTravelLocations: number;
/** ECG strips, with their rhythm verdict and their trace. */
ecgRecordings: number;
}
export function summarizeBackup(payload: BackupPayload): BackupSummary {
@@ -1751,6 +1846,14 @@ export function summarizeBackup(payload: BackupPayload): BackupSummary {
(sum, medication) => sum + medication.sideEffects.length,
0,
),
medicationEfficacyTargets: payload.medications.reduce(
(sum, medication) => sum + medication.efficacyTargets.length,
0,
),
medicationScheduleRevisions: payload.medications.reduce(
(sum, medication) => sum + medication.scheduleRevisions.length,
0,
),
moodEntries: payload.moodEntries.length,
cycles: payload.cycles.length,
cycleDayLogs: payload.cycleDayLogs.length,
@@ -1815,6 +1918,7 @@ export function summarizeBackup(payload: BackupPayload): BackupSummary {
userAchievements: payload.userAchievements.length,
environmentContexts: payload.environmentContexts.length,
environmentTravelLocations: payload.environmentTravelLocations.length,
ecgRecordings: payload.ecgRecordings.length,
};
}
+19
View File
@@ -725,6 +725,25 @@ export const updateMeasurementSchema = z.object({
.optional(),
});
/**
* Query params for `GET /api/personal-records`.
*
* Both fields used to be parsed defensively at the route: an unrecognised
* `metricType` was dropped (which WIDENED the read to every metric rather
* than narrowing it, so a typo returned more data than asked for) and a
* garbage `limit` reverted to the default. Neither told the caller anything,
* so a typo was indistinguishable from an omission. Both are refused now.
*
* The 500 ceiling matches every other paginated read on the surface, and it
* refuses rather than clamps for the same reason: silently serving 500 rows
* to a caller that asked for 999 999 is another difference nobody is told
* about.
*/
export const listPersonalRecordsSchema = z.object({
metricType: measurementTypeEnum.optional(),
limit: z.coerce.number().int().min(1).max(500).optional().default(100),
});
export const listMeasurementsSchema = z
.object({
type: measurementTypeEnum.optional(),
+56
View File
@@ -0,0 +1,56 @@
/**
* Request schemas for the two onboarding write endpoints.
*
* They live outside the route files for the same reason
* `src/lib/validations/about-me.ts` does: a route module may only export
* handlers plus the Next.js route config, so the OpenAPI registry cannot
* import a schema declared inside one. Keeping the shapes here lets the
* published contract and the runtime parser be the same object rather than
* two hand-kept copies.
*
* Prisma-free by construction — `@/lib/onboarding/goals` is pure data — so
* the generator script can pull them in without dragging the server graph
* along.
*/
import { z } from "zod/v4";
import { ONBOARDING_GOAL_SLUGS } from "@/lib/onboarding/goals";
/**
* `POST /api/onboarding/step` — the step-by-step wizard checkpoint.
*
* `step` is the step being COMPLETED and must equal the stored step plus one;
* the route refuses anything else with 409 rather than clamping. `goals`
* rides the step-2 submit and is validated against the closed slug set, so an
* unknown slug fails the whole request instead of being silently dropped.
*/
export const onboardingStepSchema = z.object({
step: z.number().int().min(1).max(4),
goals: z
.array(z.enum(ONBOARDING_GOAL_SLUGS))
.max(ONBOARDING_GOAL_SLUGS.length)
.optional(),
});
export type OnboardingStepInput = z.infer<typeof onboardingStepSchema>;
/**
* `POST /api/onboarding/complete` — the legacy single-shot completion path.
*
* Every field is optional: the endpoint's job is the completion stamp, and
* the profile fields are whatever the wizard happened to collect. A field
* that parses but is falsy (an empty `displayName`, `heightCm: 0`) is not
* written — the route only assigns truthy values.
*/
export const onboardingCompleteSchema = z.object({
displayName: z.string().trim().min(1).max(50).optional(),
heightCm: z.number().min(50).max(300).optional(),
dateOfBirth: z.string().optional(),
// The same three values the profile schema stores. A narrower enum here
// rejected the whole onboarding submission over a field the account is
// allowed to hold, and left the value unrecordable until the person found
// the setting again afterwards.
gender: z.enum(["MALE", "FEMALE", "OTHER"]).optional(),
});
export type OnboardingCompleteInput = z.infer<typeof onboardingCompleteSchema>;