# Synthetic Examples (/docs/examples)
Real, test-verified synthetic FitData documents and standalone entities read directly from the repository.
Every example below is loaded directly from `examples/` in the monorepo and validated continuously by the Vitest conformance suite. Open any of them in the [Live Validator](/validator) to edit and inspect validation output interactively.
## Training document (`examples/training.json`) [#training-document-examplestrainingjson]
A closed FitData document containing a step-based strength `training.routine`, an indoor cycling timeline `training.routine` with ramp targets and cues, a performed `training.workout`, and a `training.threshold`:
## Standalone nutrition intake (`examples/domains/nutrition/food-intake.json`) [#standalone-nutrition-intake-examplesdomainsnutritionfood-intakejson]
A `nutrition.intake` record embedding an immutable yogurt `nutrition.food` snapshot, recording 1.5 small pots (resolved to 187.5 g, 112.5 kcal, 18.75 g protein):
## Standalone lab glucose result (`examples/domains/lab/glucose-result.json`) [#standalone-lab-glucose-result-examplesdomainslabglucose-resultjson]
A `lab.result` referencing the canonical LOINC glucose test (`fitdata:glucose_serum_plasma_mass`) with a result-owned laboratory reference range:
## Revision history and tombstones (`examples/history.json`) [#revision-history-and-tombstones-exampleshistoryjson]
Demonstrates multiple revisions of a logical record and logical deletion via `core.tombstone`:
---
# Introduction (/docs)
Open draft specification and TypeScript SDK for portable fitness, nutrition, wearable, and laboratory data.
FitData is currently an unreleased draft specification. All packages, wire schemas, and registry versions use the fixed `0.0.0-local` placeholder during local iteration. No public release or backward-compatibility guarantee exists yet.
FitData defines portable, vendor-neutral data contracts for personal fitness, nutrition, wearables, sleep, and laboratory health records. It ships as a human-readable specification, generated JSON Schema files, typed TypeScript domain packages, semantic validators, JSON/JSONL serialization, and offline source mappers.
## Workspace packages [#workspace-packages]
Every domain owns its structural schemas, semantic checks, and generated JSON Schema. All four domains compose directly into the unified `fitdata` document schema using uniform `domain.noun` record kinds and optional ownership metadata.
| Package | Record kinds & scope |
| --- | --- |
| `@fitdata/core` | Shared values, IDs, time, provenance, units and conversions, optional-ownership envelopes, `core.measurement`, `core.series`, `core.summary`, `core.tombstone` |
| `@fitdata/training` | `training.routine` (step-based and timeline-based), `training.workout` (wearable and structured), `training.threshold` |
| `@fitdata/nutrition` | `nutrition.food`, `nutrition.nutrient`, `nutrition.intake`, `nutrition.meal`, `nutrition.goal`, and `createFoodIntake` serving calculations |
| `@fitdata/lab` | `lab.biomarker`, `lab.test`, `lab.specimen`, `lab.result`, `lab.report`, and the 55-biomarker / 87-test LOINC registry |
| `fitdata` | Unified document composition (all four domains + `sleep.session`), profiles, JSON/JSONL, history, and seven offline provider mappers |
## Quick example [#quick-example]
Validate a FitData document or convert external provider exports offline:
```ts
import {
currentRecords,
parseDocument,
serializeJsonLines,
validateDocument,
} from "fitdata";
import { mapStravaActivities } from "fitdata/mappers";
const mapped = mapStravaActivities(stravaPayload, {
subject: "example:athlete",
importedAt: "2026-11-29T10:00:00Z",
revision: 1,
mode: "strict",
});
if (mapped.status !== "rejected") {
const checked = validateDocument(mapped.document);
if (checked.ok) {
const active = currentRecords(checked.value);
const jsonl = serializeJsonLines(checked.value);
console.log({ activeCount: active.length, bytes: jsonl.length });
}
}
```
## Explore FitData [#explore-fitdata]
## Local workspace commands [#local-workspace-commands]
Use Node.js 22 or later inside the monorepo:
```sh
npm ci
npm run check
npm run dev:web
```
`npm run check` runs Biome linting, TypeScript builds and type checks, JSON Schema drift checks, Vitest suites, browser bundle smoke tests, offline package install checks, and the unreleased version guard.
---
# Offline Provider Mappers (/docs/mappers)
Normalize external fitness and wearable payloads into validated FitData documents with source preservation.
Import offline mappers from `fitdata/mappers`. Every mapper accepts an `unknown` input array plus an explicit `MappingContext`:
```ts
import { mapStravaActivities } from "fitdata/mappers";
const result = mapStravaActivities(items, {
subject: "example:athlete",
importedAt: "2026-11-29T10:00:00Z",
revision: 1,
mode: "strict",
});
```
Mappers never fetch remote APIs, manage OAuth tokens, write to databases, or match duplicate activities across providers. Your host application owns sync, auth, and revision allocation.
## Result contract and modes [#result-contract-and-modes]
Every mapper returns `{ status, report }` plus a validated `document` when `status` is `"complete"` or `"partial"`:
- **`strict` mode** — rejects the entire batch (`status: "rejected"`, no `document`) if any single item fails validation.
- **`partial` mode** — includes every valid item in `document` and lists rejected items in `report.issues`.
- **Warnings do not reject items.** `"complete"` means every item satisfied the mapper's contract; it does not imply every source field became a native FitData field.
`report` separates `sourceItems`, `acceptedItems`, `rejectedItems`, `outputRecords`, and `issues` (with source item index paths).
## Deterministic identity and source preservation [#deterministic-identity-and-source-preservation]
- Generated IDs are namespaced by provider, caller-supplied `subject`, and entity type. Re-importing at a later `importedAt` produces identical IDs; changing `subject` produces distinct IDs.
- Duplicate generated IDs inside one batch are rejected.
- Every mapped record retains its original JSON payload under a namespaced `source` extension (`extensions["strava:source"]`, etc.) and tags `provenance` with `kind: "imported"`, the mapper ID, and version.
- Recognized credential keys (`userAccessToken`, `access_token`, `refresh_token`, `authorization`, `client_secret`) are stripped recursively with a warning. This is a narrow credential safeguard, not a full PII scrubber.
---
# Supported Providers (/docs/mappers/providers)
Exact input dialects, emitted FitData record kinds, and explicit boundaries for all seven offline mappers.
All seven mappers live under `fitdata/mappers` and output canonical `domain.noun` records inside a validated FitData document.
| Function | Input item shape | Emitted record kinds |
| --- | --- | --- |
| `mapStravaActivities` | `{ activity, streams? }` (API activity + `key_by_type` streams) | `training.workout` + optional `core.series` |
| `mapGarminActivities` | Flat summary or `{ activityId?, summary, samples? }` | `training.workout` + optional `core.series` |
| `mapGarminDailies` | Daily summary with `summaryId`, `calendarDate`, UTC start/duration | `core.summary` (`scope: { kind: "day" }`) |
| `mapWearablesEvents` | `{ provider, dataSourceId, event }` | `training.workout` or `sleep.session` |
| `mapWearablesPoints` | `{ provider, dataSourceId, seriesType, point }` | `core.measurement` or `core.summary` |
| `mapClipinWorkouts` | Completed CLI workout detail with exercises and sets | `training.workout` (prototype) |
| `mapClipinNutrition` | CLI food-log entry with portion and macro totals | `nutrition.intake` (prototype) |
## Strava (`mapStravaActivities`) [#strava-mapstravaactivities]
- Accepts Strava API activity JSON plus optional `key_by_type` streams. Not a Strava account-export CSV parser.
- Uses absolute `start_date` (never `start_date_local`) and separates `moving_time` from `elapsed_time`.
- Maps distance, elevation gain, mean/max HR, mean/max power, mean/max speed, and `kilojoules` (mechanical work). `calories` stays `strava:calories` rather than guessing active vs total energy.
- Streams require a `time` stream and support heart rate, watts, cadence, distance, velocity, altitude, temperature, and `latlng` (paired latitude/longitude channels). Streams are conservatively labeled `downsampled`.
## Garmin (`mapGarminActivities`, `mapGarminDailies`) [#garmin-mapgarminactivities-mapgarmindailies]
- Accepts the Garmin provider payload dialect used by Convex Wearables. Not a FIT binary or Garmin Connect export parser.
- Converts UTC epoch seconds directly without double-applying `startTimeOffsetInSeconds`. Prefers `elapsedDurationInSeconds`; falls back to `durationInSeconds` with a `duration_assumption` warning.
- Dailies require an explicit `calendarDate` and do not synthesize total energy or invent a timezone.
## Convex Wearables (`mapWearablesEvents`, `mapWearablesPoints`) [#convex-wearables-mapwearablesevents-mapwearablespoints]
- Events require explicit start and end timestamps. Activity/workout events map to `training.workout`; sleep events map to `sleep.session` with visible stage gaps.
- Points cover heart rate, resting heart rate, HRV SDNN, HRV RMSSD, weight, steps, and power. Raw points emit `core.measurement`; bucketed rollups emit sample-weighted mean `core.summary`.
## CLIPIN prototypes (`mapClipinWorkouts`, `mapClipinNutrition`) [#clipin-prototypes-mapclipinworkouts-mapclipinnutrition]
- Prototype mappers for legacy CLIPIN CLI payloads. CLIPIN will adopt FitData schemas directly once mature; legacy migrations will live in the consumer repository.
- Rejects unfinished workouts and marks ambiguous nonzero loads as `clipin:recorded_weight` with a warning. Nutrition preserves logged day as a calendar date without inventing a timezone or missing micronutrients.
---
# Calculations & Unit Conversion (/docs/sdk/calculations)
Reviewed UCUM unit conversions, nutrient scaling, and immutable food intake snapshot calculations.
FitData provides pure, deterministic calculation helpers that never guess missing values, assume density, or make network requests.
## Unit conversion (`convertQuantity`) [#unit-conversion-convertquantity]
Exported from both `@fitdata/core` and `fitdata`:
```ts
import { convertQuantity } from "@fitdata/core";
const result = convertQuantity({
value: 150,
from: "[lb_av]",
to: "kg",
});
// { ok: true, value: { value: 68.0388555, unit: "kg" }, method: "fitdata:unit_conversion@1" }
```
- Covers reviewed mass, volume, energy, length, time, and temperature UCUM codes.
- Fails explicitly for unknown codes, ambiguous non-UCUM spellings (`oz`, `cup`), or cross-dimension requests (mass ↔ volume).
- Uses IEEE-754 floating-point arithmetic; retain original source quantities beside derived values.
## Food intake snapshots (`createFoodIntake`) [#food-intake-snapshots-createfoodintake]
Exported from `@fitdata/nutrition` and `@fitdata/nutrition/calculations`:
```ts
import { createFoodIntake } from "@fitdata/nutrition";
const scaled = createFoodIntake({
food: yogurtFood,
compositionId: "as-sold",
consumed: { kind: "serving", servingId: "small-pot", amount: 1.5 },
});
```
`createFoodIntake` validates the food and serving references, resolves serving equivalents, applies `composition.massVolumeEquivalent` only when mass/volume dimensions differ, scales each quantitative nutrient with method `fitdata:food_scaling@1`, preserves comparators and absent values unchanged, and embeds an immutable copy of the food definition snapshot.
## Direct nutrient scaling (`scaleNutrients`) [#direct-nutrient-scaling-scalenutrients]
Exported from `fitdata` for scaling known nutrient totals between two positive portions sharing the same unit without inventing missing nutrients or inferring density.
---
# Package Architecture (/docs/sdk)
Domain-owned TypeScript packages, strict dependency direction, and subpath exports.
FitData is organized as a Turborepo monorepo of domain-owned TypeScript packages. Each domain owns its Zod structural schemas, semantic validators, generated JSON Schema, and unit tests.
## Dependency graph [#dependency-graph]
- **`@fitdata/core`** — zero FitData dependencies. Owns shared primitives, envelopes, units, decimal comparison, JSON preflight, and `core.*` records.
- **`@fitdata/training`** → depends only on `@fitdata/core` and `zod`.
- **`@fitdata/nutrition`** → depends only on `@fitdata/core` and `zod`.
- **`@fitdata/lab`** → depends only on `@fitdata/core` and `zod`.
- **`fitdata`** (SDK) → composes `@fitdata/core`, `@fitdata/training`, `@fitdata/nutrition`, `@fitdata/lab`, plus `sleep.session`, document validation, JSON/JSONL I/O, history, and offline mappers.
Domains never import each other or the SDK, and no package depends on a database, UI framework, or network client.
## Public exports overview [#public-exports-overview]
| Package | Main entry | Subpath exports |
| --- | --- | --- |
| `@fitdata/core` | Primitives, `core.*` schemas, `validateCoreRecord`, `convertQuantity` | — |
| `@fitdata/training` | `training.*` schemas, `validateTrainingRecord`, `trainingMetrics` | `@fitdata/training/schema.json` |
| `@fitdata/nutrition` | `nutrition.*` schemas, `validateNutritionRecord`, `validateMealEntries`, `createFoodIntake` | `@fitdata/nutrition/calculations`, `@fitdata/nutrition/schema.json` |
| `@fitdata/lab` | `lab.*` schemas, `validateLabRecord`, `validateLabReportGraph`, `canonicalLabRegistry`, `findTestsByLoinc` | `@fitdata/lab/registry.json`, `@fitdata/lab/schema.json` |
| `fitdata` | `validateDocument`, `parseDocument`, `parseJsonLines`, `serializeDocument`, `serializeJsonLines`, `currentRecords`, `convertQuantity`, `scaleNutrients` | `fitdata/mappers`, `fitdata/schema.json` |
## Runtime compatibility [#runtime-compatibility]
- Targets Node.js 22+ and modern browsers (verified by `npm run smoke`, which bundles both `fitdata` and standalone `@fitdata/training` for browsers with esbuild).
- All packages ship ESM with generated `.d.ts` TypeScript declarations and JSON Schema Draft 2020-12 files.
---
# JSON Schemas & Agent Endpoints (/docs/sdk/schemas)
Download generated JSON Schema Draft 2020-12 files and LLM-friendly documentation bundles.
FitData generates JSON Schema Draft 2020-12 artifacts directly from the canonical Zod structural schemas in each package. Drift is checked automatically on every CI run via `npm run schema:check`.
## Hosted JSON Schemas [#hosted-json-schemas]
All schemas below are synced directly from the workspace packages on build:
| Artifact | Hosted URL | Package export |
| --- | --- | --- |
| Unified FitData Document | [/schemas/fitdata.schema.json](/schemas/fitdata.schema.json) | `fitdata/schema.json` |
| Training Domain | [/schemas/training.schema.json](/schemas/training.schema.json) | `@fitdata/training/schema.json` |
| Nutrition Domain | [/schemas/nutrition.schema.json](/schemas/nutrition.schema.json) | `@fitdata/nutrition/schema.json` |
| Lab Domain | [/schemas/lab.schema.json](/schemas/lab.schema.json) | `@fitdata/lab/schema.json` |
| Canonical Lab LOINC Registry | [/schemas/lab-registry.json](/schemas/lab-registry.json) | `@fitdata/lab/registry.json` |
JSON Schema validates object shape and types. Always pair structural validation with `validateDocument` (or the relevant domain validator) to enforce unit compatibility, reference resolution, timeline windows, and semantic invariants.
## Agent-friendly Markdown endpoints [#agent-friendly-markdown-endpoints]
AI coding agents and documentation tools can consume the FitData specification directly in plain text:
- [`/llms.txt`](/llms.txt) — concise index of schemas and documentation routes
- [`/llms-full.txt`](/llms-full.txt) — full processed Markdown bundle of every documentation page
---
# Serialization & History (/docs/sdk/serialization)
Parse and serialize FitData JSON and JSONL streams, and compute active record views with tombstones.
`fitdata` provides bounded text parsers, lossless serializers, and deterministic revision resolution.
## JSON documents [#json-documents]
```ts
import { parseDocument, serializeDocument } from "fitdata";
const parsed = parseDocument(jsonText);
if (parsed.ok) {
const output = serializeDocument(parsed.value);
}
```
`parseDocument` enforces the `16 MiB` UTF-8 size limit, parses JSON, and runs full `validateDocument` structural and semantic checks.
## JSON Lines (JSONL) [#json-lines-jsonl]
FitData JSONL places the document header on line 1 (all document envelope fields except `records`), followed by one JSON-serialized record per subsequent line:
```ts
import { parseJsonLines, serializeJsonLines } from "fitdata";
const jsonl = serializeJsonLines(document);
const roundTripped = parseJsonLines(jsonl);
```
- Preserves exact decimal strings, `null` series samples, extensions, and all included historical revisions.
- Rejects malformed lines, trailing invalid headers, or inputs exceeding `16 MiB` or `10,000` records.
## Active view and tombstones (`currentRecords`) [#active-view-and-tombstones-currentrecords]
Because FitData documents can include multiple revisions of the same logical `id` alongside `core.tombstone` deletions, call `currentRecords(document)` to obtain the current active set:
```ts
import { currentRecords, parseDocument } from "fitdata";
const parsed = parseDocument(historyJson);
if (parsed.ok) {
const active = currentRecords(parsed.value);
// Contains only the highest non-tombstone revision for each logical ID
}
```
Rules:
- Order of records in `document.records` never changes the output.
- If the highest revision for an `id` is a `core.tombstone`, that entity is omitted.
- Replaying a lower live revision does not undelete a tombstoned record; only a strictly higher live revision restores it.
- Versioned entities (`training.routine`, `nutrition.food`, `lab.biomarker`, `lab.test`) are keyed by `{ id, version }` and retained alongside revisioned entities.
---
# Layered Validation (/docs/sdk/validation)
Combine structural JSON Schema checks with semantic record validators and full document graph validation.
JSON Schema validates object shapes and field types, but it cannot verify cross-record revisions, metric-unit compatibility, timeline overlap rules, or recalculated nutrition snapshots. FitData therefore validates in two explicit layers.
## Layer 1: Standalone entity validation [#layer-1-standalone-entity-validation]
Use a domain validator when checking a single entity without loading a full document:
```ts
import { validateCoreRecord } from "@fitdata/core";
import { validateTrainingRecord } from "@fitdata/training";
import { validateNutritionRecord, validateMealEntries } from "@fitdata/nutrition";
import { validateLabRecord, validateLabReportGraph } from "@fitdata/lab";
const res = validateTrainingRecord(unknownInput);
if (res.ok) {
// res.value is a typed TrainingRecord
// res.issues may still contain warnings (e.g. references_unchecked)
} else {
// res.issues contains one or more severity: "error" items
}
```
Every validator returns a discriminated `ValidationResult`:
```ts
type ValidationIssue = {
code: string;
path: string; // RFC 6901 JSON Pointer
message: string;
severity: "error" | "warning";
};
type ValidationResult =
| { ok: true; value: T; issues: ValidationIssue[] }
| { ok: false; issues: ValidationIssue[] };
```
## Layer 2: Full document graph validation [#layer-2-full-document-graph-validation]
Call `validateDocument(input, options?)` from `fitdata` at every import or API boundary:
```ts
import { validateDocument } from "fitdata";
const checked = validateDocument(rawDocument);
if (!checked.ok) {
for (const issue of checked.issues) {
console.error(`[${issue.severity}] ${issue.code} at ${issue.path}: ${issue.message}`);
}
}
```
`validateDocument` runs:
1. **JSON preflight** (`inspectJson`) — rejects object cycles, non-finite numbers, unsafe integers, non-JSON values, depth `> 32`, node counts `> 1,000,000`, and `__proto__`/`constructor`/`prototype` keys.
2. **Structural parsing** (`documentSchema`) — verifies all 18 canonical record kinds and envelope constraints.
3. **Profile enforcement** — enforces `fitdata:profile.multi_subject` (effective subject required on personal records) and `fitdata:profile.audit` (document `producer` and provenance required).
4. **Domain semantics** — delegates to `checkCoreRecord`, `checkTrainingRecord`, `checkNutritionRecord`, `checkLabRecord`, and sleep stage checks.
5. **Graph & history integrity** — verifies unique `{ id, revision }` / `{ id, version }` pairs, kind/subject consistency across revisions, closed vs external references, tombstone targeting, routine `plannedStepId` resolution, lab report panel/specimen consistency, and containment/derivation cycle detection.
A valid document (`ok: true`) can still return warnings—for example when an unknown namespaced metric is preserved, or when a standalone record contains references that require document-level verification.
---
# Core & Sleep (/docs/spec/core)
Shared primitives, time variants, decimal quantities, UCUM unit subset, provenance, core.* records, and sleep.session.
`@fitdata/core` owns all shared primitives, envelopes, unit conversions, and the four cross-domain `core.*` records. It has no application or database dependency. `sleep.session` is composed in `fitdata` using the same core envelope and time primitives.
## Shared primitives [#shared-primitives]
### Namespaced codes and extensions [#namespaced-codes-and-extensions]
- Codes match `/^[a-z][a-z0-9.-]*:[A-Za-z0-9_.-]+$/` (for example `fitdata:heart_rate`, `fitdata:indoor_cycling`, `strava:calories`).
- Core objects use strict schemas that reject unknown properties.
- Vendor- or app-specific fields belong under `extensions`, keyed by namespaced identifiers (`"strava:source": { ... }`).
### Time variants [#time-variants]
FitData never invents a midnight timestamp for a calendar date or a timezone for a numeric offset:
| `kind` | Fields | Rules |
| --- | --- | --- |
| `instant` | `at` | ISO-8601 datetime with `Z` or explicit numeric UTC offset |
| `interval` | `start`, `durationSeconds` | Non-negative duration, maximum 1 year (`31,536,000` s) |
| `date` | `date`, optional `timezone` | ISO calendar date (`YYYY-MM-DD`); optional IANA timezone verified via runtime `Intl` |
### Quantities and decimal strings [#quantities-and-decimal-strings]
Quantities pair `value` with a case-sensitive `unit` string. `value` accepts either a finite safe JSON number or a decimal string (`^-?(?:0|[1-9]\d*)(?:\.\d+)?$`). Decimal strings preserve exact source digits and trailing zeros, and metric range checks use exact decimal comparison (`compareDecimal`).
### Units and conversions [#units-and-conversions]
`convertQuantity({ value, from, to })` converts finite numbers across a reviewed UCUM-aligned subset:
| Dimension | Supported codes |
| --- | --- |
| Mass | `kg`, `g`, `mg`, `ug`, `[lb_av]`, `[oz_av]` |
| Volume | `L`, `mL`, `[foz_us]`, `[foz_br]`, `[cup_us]`, `[cup_m]`, `[tbs_us]`, `[tsp_us]`, `[tbs_m]`, `[tsp_m]` |
| Energy | `kcal`, `kJ`, `J` |
| Length | `m`, `km`, `cm`, `mm`, `[mi_i]`, `[ft_i]`, `[in_i]` |
| Time | `s`, `min`, `h`, `d` |
| Temperature | `Cel`, `[degF]`, `K` |
Unknown units and cross-dimension conversions fail explicitly. `convertQuantity` never infers food density.
### Provenance [#provenance]
Optional `provenance` records how an entity was produced:
| Provenance `kind` | Required fields |
| --- | --- |
| `manual` | `source.provider` |
| `sensor` | `source.provider` |
| `imported` | `source.provider`, `mapper: { id, version }` |
| `derived` | `source.provider`, `algorithm: { id, version }`, `inputs` (references) |
`source` can also include `externalId`, `device`, and `originalSource`.
## Core record kinds [#core-record-kinds]
### `core.measurement` [#coremeasurement]
A point-in-time observation (`revision` lifecycle):
- Required: `metric` (namespaced code), `time`, `value`.
- Optional: `laterality` (`left`, `right`, `bilateral`).
- `value` is a discriminated union: `quantity`, `category` (`code`), `text`, `boolean`, or `absent` (`reason` code).
### `core.series` [#coreseries]
A sampled time-series stream (`revision` lifecycle):
- Required: `interval`, `channels` (`1–16` `{ metric, unit }` pairs), `timing`, `samples`, `resolution` (`source` or `downsampled`).
- `timing` is either `{ kind: "regular", periodSeconds }` or `{ kind: "irregular", offsetsSeconds }`.
- Every sample row width must equal `channels.length`. Missing readings are `null`. Irregular offsets must strictly increase and fit within `interval.durationSeconds`.
### `core.summary` [#coresummary]
Unified rollup for a day, interval, or meal (`revision` lifecycle):
- Required: `scope` (`{ kind: "day" }`, `{ kind: "interval" }`, or `{ kind: "meal", label }`), `time`.
- Optional: `metrics` (up to 500 `MetricAmount` entries), `totals` (up to 500 qualified nutrient totals), `completeness` (`complete`, `partial`, `unknown`), `statistic` (`sum`, `minimum`, `maximum`, `last`, `mean`), `weighting` (`sample`, `time`, `not_applicable`), `sampleCount`, `coverage`, `source`.
### `core.tombstone` [#coretombstone]
Logical deletion marker (`revision` lifecycle):
- Carries `kind: "core.tombstone"`, `id`, `revision`, and optional `recordedAt` / `provenance`.
- Contains no live domain payload.
## Sleep: `sleep.session` [#sleep-sleepsession]
Owned by `fitdata` (SDK) using the core revisioned envelope:
- Required: `interval`, `stages` (array of `{ stage, offsetSeconds, durationSeconds }`), `metrics`.
- Optional: `isNap` (boolean).
- Semantic checks guarantee sleep stages do not overlap and fit within `interval.durationSeconds`. Gaps between stages remain valid and visible.
---
# Document, Profiles & Wire Format (/docs/spec/document)
Document envelope, profiles, reference resolution, revision history, JSONL streaming format, and safety limits.
A FitData document wraps any combination of the 18 canonical record kinds into a single self-describing JSON or JSONL payload.
## Document envelope [#document-envelope]
```json
{
"format": "fitdata",
"version": "0.0.0-local",
"profiles": ["fitdata:core", "fitdata:training"],
"subject": "example:athlete",
"producer": {
"name": "example-app",
"version": "0.0.0-local"
},
"references": "closed",
"records": []
}
```
| Field | Required | Description |
| --- | --- | --- |
| `format` | Yes | Literal `"fitdata"`. |
| `version` | Yes | Wire format version (`"0.0.0-local"` in this draft). |
| `profiles` | No | Up to 50 namespaced profile codes declaring domain contracts and policy rules. |
| `subject` | No | Optional default subject ID for revisioned records that omit `subject`. |
| `producer` | No | Optional `{ name, version }` identifying the software that serialized the document. |
| `references` | Yes | `"closed"` or `"external"`. |
| `externalReferences` | Conditional | Explicit list of `{ id, revision }` or `{ id, version }` references allowed to resolve outside an `"external"` document. |
| `records` | Yes | Array of up to `10,000` canonical FitData records. |
## Document profiles [#document-profiles]
Standalone entity validation does not require ownership metadata. When a consumer needs stricter guarantees, it declares document profiles:
- **`fitdata:profile.multi_subject`** — requires an effective `subject` (either on the record or inherited from document `subject`) on every personal revisioned record.
- **`fitdata:profile.audit`** — requires `producer` on the document header as well as record provenance metadata for traceability.
Domain profiles (such as `fitdata:core`, `fitdata:training`, `fitdata:nutrition`, `fitdata:lab`) declare which domain schemas the document exercises.
## References and links [#references-and-links]
- In a **`closed`** document, every internal `{ id, revision }` or `{ id, version }` reference must resolve to a record inside `records`.
- In an **`external`** document, unresolved references must be declared explicitly in `externalReferences`.
- Resolved references cannot target a `core.tombstone` or cross subjects.
- Records can declare typed `links` with relation `part_of`, `derived_from`, or `same_activity_as`. Document validation rejects containment (`part_of`) and derivation (`derived_from`) cycles.
## Revisions and tombstones [#revisions-and-tombstones]
- `id` identifies a logical entity; `{ id, revision }` identifies an exact revision (and `{ id, version }` identifies an exact versioned definition).
- A document cannot repeat the same `{ id, revision }` or `{ id, version }` pair.
- A logical record cannot change its subject or live `kind` across revisions.
- `currentRecords(document)` computes the active view by selecting the highest revision per ID.
- If the highest revision for an ID is a `core.tombstone`, that record is excluded from the active view. Replaying an older live revision does not restore it; only a higher live revision can restore it. Input order never affects the result.
## JSON and JSONL wire formats [#json-and-jsonl-wire-formats]
FitData supports two lossless text representations:
1. **JSON** (`parseDocument` / `serializeDocument`) — a single UTF-8 JSON object matching `documentSchema`.
2. **JSONL** (`parseJsonLines` / `serializeJsonLines`) — line 1 is the document header object (the envelope without `records`), followed by one serialized record per line.
Serialization preserves decimal strings, namespaced extensions, `null` samples, and historical revisions.
## Preflight and runtime limits [#preflight-and-runtime-limits]
Preflight checks run before structural parsing and reject object cycles, non-finite numbers, non-JSON values, and prototype-pollution keys (`__proto__`, `constructor`, `prototype`).
| Limit | Value |
| --- | --- |
| JSON / JSONL payload size | `16 MiB` |
| Records per document | `10,000` |
| Samples per `core.series` | `100,000` |
| Channels per `core.series` | `16` |
| JSON nesting depth | `32` |
| Visited JSON nodes | `1,000,000` |
| Source items per mapper call | `1,000` |
| Retained semantic issues | `500` (with truncation notice) |
---
# Entity Model & Naming (/docs/spec)
Uniform domain.noun entity kinds, optional ownership metadata, and distinct version vs revision lifecycles.
FitData describes portable domain entities rather than user-owned database rows. Every top-level record follows one naming convention, one envelope model, and one explicit lifecycle.
## Core design principles [#core-design-principles]
### 1. Entities first, ownership optional [#1-entities-first-ownership-optional]
- `kind` and `id` are required on every entity.
- `subject`, `recordedAt`, `provenance`, `links`, and `extensions` are **optional** on standalone entities.
- A document can declare a default `subject` for single-person exports so individual records do not repeat it.
- Multi-user platforms, clinical stores, and audit pipelines enforce mandatory `subject`, `recordedAt`, `provenance`, or `producer` through **document profiles** rather than baking account ownership into core entity schemas.
### 2. Distinct `version` and `revision` lifecycles [#2-distinct-version-and-revision-lifecycles]
Versioning stays separate from ownership:
- **`version`** (string) identifies a release of a reusable entity or catalogue concept (`training.routine`, `nutrition.food`, `nutrition.nutrient`, `lab.biomarker`, `lab.test`). Updating a food or routine creates a new version without rewriting historical references.
- **`revision`** (positive integer) identifies a correction to a recorded event or personal state (`core.measurement`, `training.workout`, `nutrition.intake`, `lab.result`, `lab.report`).
References pin either `{ id, version }` (definition reference) or `{ id, revision }` (record reference).
### 3. Uniform `domain.noun` kind syntax [#3-uniform-domainnoun-kind-syntax]
Every top-level entity `kind` matches `^[a-z]+\.[a-z]+$`:
- Both `` and `` are single lowercase English words.
- No camelCase compounds, no redundant domain prefixes on the noun (`lab.labResult` is invalid), and no wrapper suffixes (`Entry`, `Definition`, `Concept`, `Bundle`).
- Nested discriminated unions inside an entity use short single-word tags such as `exact`, `range`, `relative`, `ramp`, `completed`, `partial`, and `skipped`.
### 4. One canonical entity per concept [#4-one-canonical-entity-per-concept]
FitData merges concepts that previously differed only by source dialect or ownership:
- **`training.workout`** covers both wearable activity summaries (`metrics`, `movingSeconds`) and structured sessions (`steps`), or both together.
- **`training.routine`** covers both reusable class blueprints (without `subject` or `scheduled`) and coach-assigned sessions (with optional `subject` and `scheduled`).
- **`core.summary`** unifies daily summaries, interval aggregates, and meal rollups under one `scope` (`day`, `interval`, `meal`).
- **Closed lab reports** use a standard FitData document with `references: "closed"` instead of a separate bundle wrapper kind.
## Canonical `kind` catalog [#canonical-kind-catalog]
All 18 top-level record kinds implemented in `0.0.0-local`:
| Kind | Package | Lifecycle | Purpose |
| --- | --- | --- | --- |
| `core.measurement` | `@fitdata/core` | `revision` | Point-in-time reading (body mass, resting HR, HRV, temperature, soreness) |
| `core.series` | `@fitdata/core` | `revision` | Sampled time-series stream (HR, power, cadence, speed, GPS) |
| `core.summary` | `@fitdata/core` | `revision` | Rolled-up totals or statistics for a day, meal, or interval |
| `core.tombstone` | `@fitdata/core` | `revision` | Deletion marker for an exact `{ id, revision }` |
| `sleep.session` | `fitdata` | `revision` | Sleep interval, nap flag, stages, and sleep metrics |
| `training.routine` | `@fitdata/training` | `version` | Reusable or scheduled session blueprint (steps or timed segments, targets, cues) |
| `training.workout` | `@fitdata/training` | `revision` | Performed exercise session (sport, interval, status, summary metrics, optional steps) |
| `training.threshold` | `@fitdata/training` | `revision` | Reference performance value (FTP, max HR, 1RM) |
| `nutrition.food` | `@fitdata/nutrition` | `version` | Food item, servings, and nutrient compositions |
| `nutrition.nutrient` | `@fitdata/nutrition` | `version` | Nutrient concept, preferred unit, and external codes |
| `nutrition.intake` | `@fitdata/nutrition` | `revision` | Logged consumption of a food snapshot or direct nutrients |
| `nutrition.meal` | `@fitdata/nutrition` | `revision` | Named group of exact `nutrition.intake` revisions |
| `nutrition.goal` | `@fitdata/nutrition` | `revision` | Target nutrient amounts starting on an effective calendar date |
| `lab.biomarker` | `@fitdata/lab` | `version` | Analyte or biomarker concept |
| `lab.test` | `@fitdata/lab` | `version` | Measurable lab assay (biomarker, specimen, property, scale, method, units, LOINC) |
| `lab.specimen` | `@fitdata/lab` | `revision` | Biological sample metadata and collection time |
| `lab.result` | `@fitdata/lab` | `revision` | Single laboratory test result with raw text, typed value, status, review, and ranges |
| `lab.report` | `@fitdata/lab` | `revision` | Laboratory report grouping panels, specimens, and results |
## Versioning boundaries [#versioning-boundaries]
FitData keeps five version concepts strictly separate:
1. **Package version** identifies executable code and public TypeScript APIs.
2. **Schema version** identifies the serialized domain contract.
3. **Definition version** identifies a specific food, nutrient, routine, biomarker, or lab test definition.
4. **Record revision** identifies a correction to a person's recorded event or result.
5. **Mapper / calculation version** identifies transformation behavior.
---
# Laboratory & Biomarkers (/docs/spec/lab)
Lab biomarkers, tests, specimens, results, reports, result-owned reference ranges, and the 55-biomarker / 87-test LOINC registry.
`@fitdata/lab` models laboratory biomarkers, assays, specimens, individual results, and multi-panel reports. It ships with a reviewed registry of **55 biomarkers** and **87 source-verified tests** with aliases, supported units, and LOINC mappings.
## Record kinds [#record-kinds]
| Kind | Lifecycle | Meaning |
| --- | --- | --- |
| `lab.biomarker` | `version` | Analyte or biomarker concept with localized names, aliases, and description |
| `lab.test` | `version` | Measurable lab assay specifying biomarker, specimen types, property, scale, method, supported units, and external code mappings |
| `lab.specimen` | `revision` | Biological sample metadata (`type` coding, collection time, optional collection method and body site) |
| `lab.result` | `revision` | Single test result with raw source text, typed value, status, review state, optional specimen ref, and result-specific reference ranges |
| `lab.report` | `revision` | Laboratory report grouping optional presentation `panels`, `specimens`, and exact `results` revisions |
## Result values and missing data [#result-values-and-missing-data]
Lab reports contain censored readings, qualitative outcomes, blank cells, and unrecognized local test codes. FitData represents each explicitly instead of inventing zeros or dropping data:
| Source case | FitData representation |
| --- | --- |
| Numeric reading (e.g. `92 mg/dL`) | `value: { kind: "quantity", comparator: "=", value: "92", unit: "mg/dL" }` |
| Below detection limit (e.g. `<0.5 mg/L`) | `value: { kind: "quantity", comparator: "<", value: "0.5", unit: "mg/L" }` |
| Qualitative result (e.g. urine glucose negative) | `value: { kind: "category", code: "..." }` |
| Narrative comment | `value: { kind: "text", text: "..." }` |
| Test not performed or blank cell | `value: { kind: "absent", reason: "..." }` with `raw.value` preserved |
| Unrecognized assay | `test: { kind: "unresolved", label: "..." }` — measured value stays intact |
## Result-owned reference ranges [#result-owned-reference-ranges]
Reference ranges belong on each `lab.result`, never on canonical test definitions:
- `canonicalLabRegistry` intentionally contains **no default ranges**.
- A `numeric` range carries `purpose` (`reference`, `decision_limit`, `target`), `sourceKind` (`laboratory` or `external`), `source`, `unit`, optional `low` / `high`, and optional `lowInclusive` / `highInclusive`.
- Omitted inclusivity means unknown; plain interval notation does not invent strict bounds.
- A `text` range preserves narrative or population-stratified ranges verbatim.
## Closed report graphs [#closed-report-graphs]
Reports compose natively inside a standard FitData document with `references: "closed"`, or validate directly via `validateLabReportGraph`:
```ts
import {
canonicalLabRegistry,
findTestsByLoinc,
validateLabRecord,
validateLabReportGraph,
} from "@fitdata/lab";
const glucoseTests = findTestsByLoinc("2345-7");
const checked = validateLabRecord(resultInput, canonicalLabRegistry);
```
Graph validation verifies exact `{ id, revision }` references for specimens and results, unique panel IDs, report membership, subject consistency, and specimen-to-test compatibility (including whole blood supplying erythrocyte material for corpuscular indices).
## Canonical LOINC registry [#canonical-loinc-registry]
Browse all 55 biomarkers and 87 reviewed tests shipped in `@fitdata/lab` (raw JSON available at [/schemas/lab-registry.json](/schemas/lab-registry.json)):
This registry includes source-verified LOINC code mappings. LOINC® is a registered trademark of Regenstrief Institute, Inc. See `packages/lab/LOINC_short_license.txt` in the repository for required attribution notices.
---
# Nutrition (/docs/spec/nutrition)
Food and nutrient definitions, historical intake snapshots, serving calculations, meals, goals, and capture provenance.
`@fitdata/nutrition` defines portable nutrition contracts without coupling to a commercial food database, provider, or application schema.
## Record kinds [#record-kinds]
| Kind | Lifecycle | Meaning |
| --- | --- | --- |
| `nutrition.food` | `version` | Versioned generic, branded, restaurant, prepared, or custom food with servings and compositions |
| `nutrition.nutrient` | `version` | Versioned nutrient concept, preferred unit, and external codes |
| `nutrition.intake` | `revision` | Logged consumption carrying an immutable food snapshot or directly reported nutrient totals |
| `nutrition.meal` | `revision` | Named group of exact `nutrition.intake` revisions |
| `nutrition.goal` | `revision` | Target nutrient amounts starting on an effective calendar date |
Meal and daily rollups without item breakdowns use `core.summary` from `@fitdata/core`. `subject`, `recordedAt`, and `provenance` are optional on standalone entities.
## Food identity, compositions, and servings [#food-identity-compositions-and-servings]
- A `nutrition.food` carries localized `names`, `foodType`, `sources`, `identifiers` (barcodes stored as strings), `servings`, and `compositions`, plus optional `brand` and `derivedFrom`.
- Each composition has a local `id`, preparation `state` (`raw`, `cooked`, `as_sold`, `prepared`, `unknown`), `basis` (mass, volume, or named serving), and `nutrients`.
- Each serving declares `amount`, `compositionIds` (the exact compositions it applies to), and optional `equivalent` (mass or volume). `serving.amount` is the count represented by `equivalent`—for example, `amount: 2` with `equivalent: 30 g` means 1 serving = 15 g.
- Converting between mass and volume requires an explicit `composition.massVolumeEquivalent` with a supporting source. No default water density is assumed.
## Units and portion codes [#units-and-portion-codes]
Mass and volume fields use explicit case-sensitive UCUM codes from `@fitdata/core`:
- **Mass:** `kg`, `g`, `mg`, `ug`, `[lb_av]`, `[oz_av]`
- **Volume:** `L`, `mL`, `[foz_us]`, `[foz_br]`, `[cup_us]`, `[cup_m]`, `[tbs_us]`, `[tsp_us]`, `[tbs_m]`, `[tsp_m]`
- **Energy:** `kcal`, `kJ`, `J`
Unqualified `cup`, `oz`, or `spoon` codes are rejected because mass ounces, US fluid ounces, and British fluid ounces differ.
## Historical intake snapshots [#historical-intake-snapshots]
`nutrition.intake` uses a discriminated `intake` union:
| `intake.kind` | Contents |
| --- | --- |
| `food` | Full embedded `snapshot` of the `nutrition.food` at logging time, `compositionId`, original `consumed` portion, and `nutrition` result |
| `nutrients` | Display `name` and nutrient `totals`, without inventing a fake food item |
Embedding the food snapshot guarantees that later catalogue edits never silently mutate historical diary entries. Food intake `nutrition` takes one of three explicit forms:
- **`calculated`** — method `fitdata:food_scaling@1`, `resolvedAmount`, and scaled totals.
- **`reported`** — source totals plus source reference (used when imported labels or historical totals differ from fresh scaling).
- **`unavailable`** — coded reason; missing conversions or nutrients are never coerced to zero.
Omitted nutrients remain unknown. The calculator never substitutes salt for sodium, infers calories from macros, or merges incompatible carbohydrate definitions.
## Serving calculation contract [#serving-calculation-contract]
`createFoodIntake({ food, compositionId, consumed })` builds and validates a complete `food` intake payload offline:
```ts
import { createFoodIntake, validateNutritionRecord } from "@fitdata/nutrition";
const intakeBody = createFoodIntake({
food: yogurtFood,
compositionId: "as-sold",
consumed: { kind: "serving", servingId: "small-pot", amount: 1.5 },
});
if (intakeBody.ok) {
const checked = validateNutritionRecord({
kind: "nutrition.intake",
id: "example:intake-yogurt",
revision: 1,
time: { kind: "instant", at: "2026-11-01T08:30:00+01:00" },
intake: intakeBody.value,
});
console.log(checked.ok);
}
```
Semantic validation recalculates `calculated` totals from the saved snapshot and checks matching nutrient IDs/versions, units, comparators, and numeric values within a `1e-12` relative tolerance (with zero required to remain zero).
## Meals and capture provenance [#meals-and-capture-provenance]
- `nutrition.meal` owns the relationship via an ordered array of exact `{ id, revision }` intake references. Intakes carry no `mealId` field that could disagree.
- `validateMealEntries({ meal, entries })` checks every referenced revision, rejects duplicate IDs, extra unreferenced entries, self-references, and subject mismatches.
- Optional `capture` records how an entry was logged (`fitdata:manual`, `fitdata:barcode_scan`, `fitdata:meal_photo`, `fitdata:nutrition_label_photo`, `fitdata:text`, `fitdata:import`), source evidence, optional algorithm ID/version, and review state (`unreviewed`, `confirmed`, `corrected`).
---
# Training (/docs/spec/training)
Training routines (step-based and timed timelines), performed workouts, thresholds, targets, ramps, and load bases.
`@fitdata/training` defines portable training contracts independently of any application or database. It covers strength sessions, timed indoor classes, wearable activities, and personal performance thresholds.
## Record kinds [#record-kinds]
| Kind | Lifecycle | Required training fields | Optional fields |
| --- | --- | --- | --- |
| `training.routine` | `version` | `name`, namespaced `sport`, `structure` (`steps` or `timeline`) | `description`, `scheduled` |
| `training.workout` | `revision` | Namespaced `sport`, `interval` | `name`, `movingSeconds`, `routine`, `status`, `metrics`, `steps`, `sessionRpe` |
| `training.threshold` | `revision` | `metric`, `quantity`, `effectiveAt`, `method` (`tested` or `estimated`) | `basis`, `exercise` |
- **`training.workout`** unifies wearable activity summaries (`metrics`, `movingSeconds`) and structured exercise logs (`steps`). `movingSeconds` cannot exceed `interval.durationSeconds`.
- **`training.routine`** unifies reusable class blueprints (no `subject`, no `scheduled`) and athlete-assigned sessions (optional `subject` and `scheduled`).
## Routine structures [#routine-structures]
A `training.routine` declares one of two execution layouts in `structure`:
### Step-based (`structure.kind: "steps"`) [#step-based-structurekind-steps]
Built for strength, mobility, and circuit training where duration follows execution pace:
- `steps`: `1–1,000` ordered planned steps.
- Each step has a local `id`, `exercise` (`{ id, name? }`), `1–20` metric `targets`, and optional `role`, `load`, `restSeconds`, and `side`.
### Timeline-based (`structure.kind: "timeline"`) [#timeline-based-structurekind-timeline]
Built for indoor cycling classes, erg workouts, and timed audio sessions running on an elapsed clock:
- `durationSeconds`: total class duration.
- `segments`: ordered, non-overlapping windows with `id`, `startSeconds`, `endSeconds`, `1–20` `targets`, and optional `label` and `role`.
- `cues` (optional): timed cues with `atSeconds` and at least one of `posture`, `resistance`, or `text`.
Presentation concerns (music playlists, video overlays, player themes) stay outside FitData or under namespaced `extensions`.
```json
{
"kind": "training.routine",
"id": "example:five-minute-climb",
"version": "1",
"sport": "fitdata:indoor_cycling",
"name": "Five-minute climb",
"structure": {
"kind": "timeline",
"durationSeconds": 300,
"segments": [
{
"id": "climb",
"startSeconds": 0,
"endSeconds": 300,
"targets": [
{
"metric": "fitdata:power",
"target": {
"kind": "ramp",
"basis": "fitdata:ftp",
"unit": "%",
"start": 70,
"end": 85,
"interpolation": "linear"
}
},
{
"metric": "fitdata:cadence",
"target": {
"kind": "range",
"unit": "/min",
"min": 75,
"max": 85
}
}
]
}
],
"cues": [
{ "atSeconds": 0, "posture": "seated", "text": "Start seated." },
{ "atSeconds": 180, "posture": "standing", "text": "Stand for the final two minutes." }
]
}
}
```
## Performed steps and results [#performed-steps-and-results]
Performed steps inside `training.workout` carry local `id`, `exercise`, tagged `result`, and optional `plannedStepId`, `role`, and `side`.
- `completed` or `partial` results carry `1–20` metric amounts plus optional `load` and `rpe` (`0–10`).
- `skipped` results require a `reason`.
- Setting `plannedStepId` requires a `routine` reference (`{ id, version }`) on the workout, and document validation verifies that `plannedStepId` exists in that routine version's steps or segments.
## Targets and loads [#targets-and-loads]
Every target pairs a namespaced `metric` with a tagged `target`:
| Target `kind` | Fields and rules |
| --- | --- |
| `exact` | Quantity `value` and `unit` |
| `range` | `min`, `max`, and `unit`; `min <= max` |
| `relative` | Non-negative `fraction` plus `basis` code (e.g. `fitdata:ftp`), pinned `threshold` reference, or both |
| `ramp` | `start`, `end`, `unit`, optional `interpolation` (`linear` or `step`), plus optional `basis` or pinned `threshold` (relative ramps require `%` or `1`) |
Using a `basis` code without a pinned `threshold` lets one routine be shared across athletes and resolved dynamically against each athlete's active `training.threshold`. When a `threshold` reference is pinned, its metric must match the target metric.
Loads separate magnitude from mechanical meaning:
| `basis` | Meaning | Allowed units |
| --- | --- | --- |
| `external_total` | Total external load | `kg`, `[lb_av]` |
| `external_per_hand` | External load per hand | `kg`, `[lb_av]` |
| `added` | Load added to bodyweight | `kg`, `[lb_av]` |
| `assisted` | Positive assistance magnitude | `kg`, `[lb_av]` |
| `bodyweight_fraction` | Fraction of bodyweight | `1` |
## Validation entry points [#validation-entry-points]
```ts
import { validateTrainingRecord, type Workout } from "@fitdata/training";
const result = validateTrainingRecord(input);
if (result.ok && result.value.kind === "training.workout") {
const workout: Workout = result.value;
console.log(workout.sport, result.issues);
}
```
`validateTrainingRecord` checks local structure, quantities, loads, ramps, segment windows, cues, local step IDs, and scheduled timezones. Run `validateDocument` from `fitdata` to verify cross-record routine and threshold references.