> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/reference/mobile-sdks/react-native-sdk-2.md).

# React Native SDK

Every method and type in @tryterra/react-native 2.x, the React Native SDK: signatures, parameters, return values and error codes.

{% hint style="info" %}
This is the reference for `@tryterra/react-native` 2.3.0. For setup and a walkthrough, read the [React Native SDK guide](https://docs.tryterra.co/mobile-sdks/react-native-sdk-2).
{% endhint %}

```typescript
import { createTerra, EndUser, TerraError } from '@tryterra/react-native';
```

Every method returns a promise, and every rejection is a [`TerraError`](#terraerror). A member listed under [Android-only methods](#android-only-methods) or [iOS-only methods](#ios-only-methods) is typed as optional (or `undefined`) and is absent on the other platform, so check it before you call it.

## Sources

| Value             | Platform     | Description                                                                                                                                  |
| ----------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `'health'`        | iOS, Android | Apple Health on iOS, Health Connect on Android                                                                                               |
| `'samsungHealth'` | Android      | Samsung Health, read directly. Needs the Samsung add-on and `terraSamsungHealth=true`, otherwise calls reject with `health_data_unavailable` |

Every call that takes a `source` defaults to `'health'`.

## Data categories

```typescript
type DataCategory = 'activity' | 'body' | 'daily' | 'sleep' | 'nutrition' | 'menstruation' | 'athlete' | 'clinicalRecord'
```

Request them with [`permissions.request`](#permissions.request). Heart rate is uploaded on the daily route. Its permission comes with `body` on iOS and with `daily` on Android. To ask for single types instead of whole categories, use [`HealthDataType`](#healthdatatype).

`menstruation` and `athlete` are available in 2.2.1 and later, and are read only. `athlete` is iOS only: a request that names it on Android rejects with `bridge.unsupported_on_platform`.

`clinicalRecord` is Apple Health Records, iOS only, available in 2.3.0 and later. `permissions.request` ignores it. Ask for it with [`permissions.requestClinicalRecords`](#permissions.requestclinicalrecords).

## Types

### TerraOptions

```typescript
type TerraOptions = {
  tokenProvider?: TokenProvider;   // returns a one-time auth token from your backend
  tokenTimeoutMs?: number;         // default 30000
};
```

* `tokenProvider` is called only while `connect` makes a new link and was given no token. A restored link and a background run never call it.
* After `tokenTimeoutMs`, `connect` rejects with `bridge.token_timeout` on iOS and `token_provider_failed` on Android.

### TokenProvider

```typescript
type TokenProvider = () => Promise<string>
```

A rejection is passed to the native side, and `connect` rejects with `token_provider_failed`.

### EndUser

Who a connect is for. A stored link is restored only for the person it was made for. The value never leaves the device as identity: Terra trusts only the `reference_id` inside the token.

```typescript
type EndUser = { kind: 'reference'; id: string } | { kind: 'anonymous' }

EndUser.reference(id: string): EndUser   // the person your backend mints the token for
EndUser.anonymous: EndUser               // nobody your backend tracks
```

### Connection

```typescript
type Connection = {
  source: Source;              // the linked store
  userId: string;              // Terra's user ID for this link
  providerUserId?: string;     // Android only. The store-side ID
};
```

### HealthAccess

```typescript
type HealthAccess = {
  read: readonly DataCategory[];          // categories to read
  write: readonly DataCategory[];         // categories to write
  workouts: readonly WorkoutScope[];      // workout types to write
  readTypes?: readonly HealthDataType[];  // single types to read. 2.3.0 and later
};
```

* `write: ['activity']` asks for workouts and everything a workout can carry.
* `workouts` is for an app that logs only some workout types. Leave `activity` out of `write` when you use it.
* `readTypes` asks for single types instead of whole categories. See [`HealthDataType`](#healthdatatype). In what [`permissions.requested`](#permissions.requested) returns, it is absent for an app that asked only by category.

### HealthDataType

One kind of health data, at the level a permission sheet can ask for it. Pass it in `readTypes` to ask for exactly the types your app discloses instead of a whole category. Available in 2.3.0 and later.

```typescript
type HealthDataType =
  | 'steps' | 'activeEnergy' | 'basalEnergy' | 'distance' | 'floorsClimbed'
  | 'swimmingStrokes' | 'exerciseTime' | 'moveTime' | 'standTime'          // iOS only
  | 'heartRate' | 'restingHeartRate' | 'sleepAnalysis'
  | 'workouts' | 'workoutRoute' | 'speed' | 'power' | 'cyclingCadence'
  | 'weight' | 'height' | 'bodyFat' | 'leanBodyMass' | 'bloodPressure' | 'bloodGlucose'
  | 'oxygenSaturation' | 'bodyTemperature' | 'heartRateVariability' | 'respiratoryRate' | 'vo2Max'
  | 'bmi' | 'waistCircumference' | 'insulinDelivery' | 'heartbeatSeries' | 'electrocardiogram'  // iOS only
  | 'boneMass' | 'bodyWaterMass'                                                                // Android only
  | 'dietaryEnergyConsumed' | 'dietaryProtein' | 'dietaryCarbohydrates' /* ...one per Nutrient */ | 'dietaryWater'
  | 'menstrualFlow' | 'intermenstrualBleeding' | 'ovulationTest' | 'cervicalMucus' | 'sexualActivity'
  | 'pregnancyTest' | 'progesteroneTest' | 'pregnancy' | 'lactation' | 'contraceptive'
  | 'persistentIntermenstrualBleeding' | 'infrequentCycles' | 'irregularCycles'
  | 'prolongedPeriods' | 'bleedingDuringPregnancy' | 'bleedingAfterPregnancy'                  // iOS only
  | 'biologicalSex' | 'dateOfBirth' | 'wheelchairUse' | 'activityMoveMode'                     // iOS only
```

There is one dietary type per [`Nutrient`](#read-value-types), named `dietary` plus the nutrient with a capital first letter: `dietaryEnergyConsumed`, `dietaryProtein`, through `dietaryPantothenicAcid`. The package also exports every value as `HealthDataTypeValues`. The [Permissions](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping#individual-types) page lists the HealthKit and Health Connect types behind each one.

Once a request names any type, the install is type-scoped:

* The SDK reads, observes and uploads only the requested types, plus every type of a category you also asked for whole. A type you never requested is never read.
* A payload leaves out the fields of types you did not request. They are absent, not zero. A daily payload carries only the requested day totals. A workout carries its energy, distance and steps only when `activeEnergy`, `distance` and `steps` are requested too.
* The upload does not say which types you requested. Request every type the payloads you rely on need.
* A category your app only writes is no longer read back.
* Types join the running union of everything requested, so a later request adds to them and never removes any.

An app that never passes `readTypes`, or passes it empty, keeps the category behaviour.

`workoutRoute`, `speed`, `power` and `cyclingCadence` are read through the workouts they belong to. A request whose running union holds one of them without `workouts`, or `activity` asked for whole, rejects with `workouts_required`, naming the type in `details.type`, before anything is recorded or shown.

A type the platform has no store type for rejects with `bridge.unsupported_on_platform` before anything is recorded. So does any type asked of `'samsungHealth'`, which is asked by category only.

{% hint style="warning" %}
**Moving from categories to types on Android.** Health Connect's `sleep` category also asks for heart rate, resting heart rate, heart rate variability, oxygen saturation and respiratory rate. An app that replaces `read: ['sleep']` with `readTypes: ['sleepAnalysis']` stops reading them. Add `heartRate`, `restingHeartRate`, `heartRateVariability`, `oxygenSaturation` and `respiratoryRate` to keep them.
{% endhint %}

### WorkoutScope

```typescript
type WorkoutScope = {
  activity: WorkoutActivity;   // the workout type
  energy: boolean;             // also write active energy
  distance: boolean;           // also write distance
};
```

### PermissionStatus

| Value           | Platform     | Meaning                                                                                                  |
| --------------- | ------------ | -------------------------------------------------------------------------------------------------------- |
| `granted`       | iOS, Android | Allowed. On iOS, reported for writes only                                                                |
| `denied`        | iOS, Android | Refused. On iOS, reported for writes only                                                                |
| `notDetermined` | iOS, Android | Not asked yet                                                                                            |
| `notDisclosed`  | iOS          | Asked, and the platform will not say what the person chose. iOS reads always answer this                 |
| `unsupported`   | iOS, Android | Nothing on the device can serve this category. Android also answers this where iOS answers `unavailable` |
| `unavailable`   | iOS          | The device has no Apple Health. Hide the feature                                                         |

### TimeRange

A half-open window `[start, end)`, resolved against the device's calendar.

```typescript
type TimeRange =
  | { kind: 'lastHours'; hours: number }
  | { kind: 'lastDays'; days: number }
  | { kind: 'today' }
  | { kind: 'between'; start: Date; end: Date }
```

### Samples

Every sample carries `source: SampleSource`, `userEntered: boolean` and an optional `timeZone`.

| Type              | Fields                                                                                                                                                 |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `HeartRateSample` | `id`, `time: Date`, `beatsPerMinute`, `motionContext?: 'unknown' \| 'sedentary' \| 'active'`                                                           |
| `StepCount`       | `id?`, `start: Date`, `end: Date`, `steps`                                                                                                             |
| `SleepSegment`    | `id`, `start: Date`, `end: Date`, `stage: SleepStage`                                                                                                  |
| `Workout`         | `id`, `start: Date`, `end: Date`, `activity: WorkoutActivity`, `activityTypeCode`, `indoor?`, `activeEnergyKilocalories?`, `distanceMeters?`, `title?` |
| `SampleSource`    | `name`, `bundleId`, `productType?`, `deviceType?`                                                                                                      |

`Workout.title` is the name the writing app gave the session: `ExerciseSessionRecord.title` on Android, and `HKMetadataKeyWorkoutBrandName` on iOS, which has no title field. Available in 2.2.1 and later.

The samples below are available in 2.2.1 and later.

| Type                     | Fields                                                                                                                                                                  |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `RestingHeartRateSample` | `id`, `start: Date`, `end: Date`, `beatsPerMinute`                                                                                                                      |
| `DayTotal`               | `metric: DayTotalMetric`, `start: Date`, `end: Date`, `value`, `unit`, `timeZone?`. `start` and `end` are the day's local midnights. No `id`, `source` or `userEntered` |
| `IntradaySample`         | `id`, `metric: IntradayMetric`, `start: Date`, `end: Date`, `value`                                                                                                     |
| `BodyReading`            | `id`, `kind: BodyReadingKind`, `start: Date`, `end: Date`. A point reading has `start` equal to `end`; skin and wrist temperature span a stretch                        |
| `WorkoutRoute`           | `id`, `workoutId`, `start: Date`, `end: Date`, `points: RoutePoint[]`. At most one point a second and at most 5,000 points. No `userEntered`                            |
| `RoutePoint`             | `time: Date`, `latitude`, `longitude`. Not a sample: no `source`                                                                                                        |
| `WorkoutIntensitySample` | `id`, `metric: WorkoutIntensityMetric`, `workoutId?`, `start: Date`, `end: Date`, `value`. On Android `workoutId` is absent and `start` equals `end`                    |
| `HydrationSample`        | `id`, `start: Date`, `end: Date`, `millilitres`                                                                                                                         |
| `DietaryQuantity`        | `id`, `nutrient: Nutrient`, `value`, `start: Date`, `end: Date`, `mealType: MealType`, `name?`, `foodCorrelationId?`                                                    |
| `MenstruationFlowDay`    | `id`, `start: Date`, `end: Date`, `flow: MenstruationFlow`, `cycleStart: boolean`. `start` and `end` are the day's local midnights                                      |
| `MenstrualEvent`         | `id`, `kind: MenstrualEventKind`, `time: Date`, `value?`, `storeIdentifier`                                                                                             |
| `AthleteProfile`         | iOS only. `biologicalSex: BiologicalSex`, `dateOfBirth?: string`, `wheelchairUse?: boolean`, `activityMoveMode?: ActivityMoveMode`. Not a sample: no `id` or `source`   |

* `DietaryQuantity.value` is in the nutrient's fixed unit: kcal for `energyConsumed`, grams for `protein`, `carbohydrates`, the four fats, `sugar` and `fiber`, and milligrams for the rest. Quantities of one meal share `foodCorrelationId`. It is always set on Android, where it is the meal's record ID and the ID `nutrition.delete` takes for a meal your app logged. On iOS it is absent for a quantity HealthKit did not group into a meal.
* `MenstrualEvent.value` is `negative`, `positive`, `high`, `indeterminate` or `luteinizingHormoneSurge` for `ovulationTest`, and `dry`, `sticky`, `creamy`, `watery`, `eggWhite` or `unusual` for `cervicalMucus`. It is absent for `intermenstrualBleeding`, which is a flag. `storeIdentifier` is the store's own record type, such as `OvulationTestRecord` on Android.
* `AthleteProfile.dateOfBirth` is a calendar day, as HealthKit stores it, never an instant.

### Read value types

Available in 2.2.1 and later.

```typescript
type DayTotalMetric =
  | 'distanceWalkingRunning' | 'distanceCycling' | 'distanceSwimming' | 'distanceWheelchair'  // metres
  | 'activeEnergyBurned' | 'basalEnergyBurned'                                                // kcal
  | 'flightsClimbed'                                                                           // count
  | 'appleExerciseTime';                                                                       // minutes, iOS only
type IntradayMetric = 'activeEnergy' | 'basalEnergy' | 'distance' | 'floorsClimbed';  // basalEnergy iOS only
type WorkoutIntensityMetric = 'speed' | 'power' | 'cadence';  // m/s, watts, pedal revolutions per minute
type MenstruationFlow = 'unspecified' | 'light' | 'medium' | 'heavy' | 'none';
type MenstrualEventKind = 'intermenstrualBleeding' | 'ovulationTest' | 'cervicalMucus';
type MealType = 'breakfast' | 'lunch' | 'dinner' | 'snack' | 'unknown';  // always 'unknown' on iOS
type BiologicalSex = 'female' | 'male' | 'other' | 'notSet';  // iOS only
type ActivityMoveMode = 'activeEnergy' | 'appleMoveTime';      // iOS only
```

`Nutrient` has 38 values, the HealthKit dietary identifiers without the `HKQuantityTypeIdentifierDietary` prefix and with a lower-case first letter: `energyConsumed`, `protein`, `carbohydrates`, `fatTotal`, `fatSaturated`, `fatMonounsaturated`, `fatPolyunsaturated`, `sugar`, `fiber`, `cholesterol`, `sodium`, `potassium`, `calcium`, `iron`, `magnesium`, `zinc`, `phosphorus`, `iodine`, `manganese`, `molybdenum`, `selenium`, `copper`, `chromium`, `chloride`, `caffeine`, `vitaminA`, `vitaminC`, `vitaminD`, `vitaminE`, `vitaminK`, `vitaminB6`, `vitaminB12`, `thiamin`, `riboflavin`, `niacin`, `folate`, `biotin` and `pantothenicAcid`.

### BodyReadingKind

What a [`BodyReading`](#samples) measured. The variant fixes the unit. Available in 2.2.1 and later.

```typescript
type BodyReadingKind =
  | { type: 'measurement'; metric: BodyMetric; value: number }
  | { type: 'bloodPressure'; systolic: number; diastolic: number }                  // mmHg
  | { type: 'bloodGlucose'; value: number; unit: 'mg/dL' | 'mmol/L';
      mealTime?: 'preprandial' | 'postprandial' | 'unknown';
      specimen?: 'capillary' | 'interstitial' | 'plasma' | 'serum' | 'tears' | 'wholeBlood' | 'unknown' }
  | { type: 'oxygenSaturation'; fraction: number }                                  // 0..1
  | { type: 'temperature'; metric: 'body' | 'basal' | 'wrist' | 'skin'; celsius: number }
  | { type: 'heartRateVariability'; metric: 'sdnn' | 'rmssd'; milliseconds: number }
  | { type: 'respiratoryRate'; breathsPerMinute: number }
  | { type: 'vo2Max'; millilitresPerKilogramMinute: number;
      testType?: 'maxExercise' | 'predictedSubMaxExercise' | 'predictedNonExercise' }

type BodyMetric = 'weight' | 'height' | 'bodyFatPercentage' | 'leanBodyMass' | 'bmi'
```

* `BodyMetric`: `weight` and `leanBodyMass` are kilograms, `height` centimetres, `bodyFatPercentage` a fraction from 0 to 1, and `bmi` has no unit. `bmi` is iOS only.
* Blood glucose keeps the unit the writing app chose. It is never converted on the device.
* `body` and `basal` temperatures are absolute. `wrist` and `skin` are differences from a baseline and are often negative. `wrist` is iOS only.
* iOS records heart rate variability as `sdnn` only, and Android as `rmssd` only.

### StoreAvailability

Whether the device can serve a source. Available in 2.2.1 and later.

```typescript
type StoreAvailability =
  | { kind: 'available' }
  | { kind: 'unsupportedDevice' }                     // iOS only
  | { kind: 'providerAppMissing' }                    // Android only
  | { kind: 'providerAppTooOld'; installed: string }  // Android only
  | { kind: 'moduleMissing' }                         // Android only
  | { kind: 'partnerPolicyMissing' }                  // Android only
  | { kind: 'featureUnavailable' }                    // Android only
```

* `unsupportedDevice`: the device has no HealthKit store. No permission or update changes that.
* `providerAppMissing`: Health Connect is not installed on Android 13 or below, or Samsung Health is not installed.
* `providerAppTooOld`: the provider app needs an update. `installed` is its version.
* `moduleMissing`: `'samsungHealth'` was asked for without the Samsung add-on.
* `partnerPolicyMissing` and `featureUnavailable` do not carry the types or the feature. The native Android report does.

### SleepStage

```typescript
type SleepStage =
  | { kind: 'inBed' } | { kind: 'awake' } | { kind: 'asleep' }
  | { kind: 'light' } | { kind: 'deep' } | { kind: 'rem' }
  | { kind: 'unknown'; raw: string }
```

### WorkoutActivity

```typescript
type WorkoutActivity =
  | { kind: 'running' } | { kind: 'walking' } | { kind: 'cycling' }
  | { kind: 'swimming' } | { kind: 'strengthTraining' }
  | { kind: 'other'; label: string }
```

### Entries

Every entry takes an optional `recordId`, your own ID for the record.

| Type             | Fields                                                                                                                                                                                                                                                                                                         |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HeartRateEntry` | `time: Date`, `beatsPerMinute: number`                                                                                                                                                                                                                                                                         |
| `StepEntry`      | `start: Date`, `end: Date`, `steps: number`                                                                                                                                                                                                                                                                    |
| `SleepEntry`     | `start: Date`, `end: Date`, `stage: SleepStage`                                                                                                                                                                                                                                                                |
| `WorkoutEntry`   | `start: Date`, `end: Date`, `activity: WorkoutActivity`, `totalEnergyKilocalories?`, `totalDistanceMeters?`                                                                                                                                                                                                    |
| `BodyEntry`      | `time: Date`, and any of `bodyMassKilograms`, `bodyFatPercent`, `bodyMassIndex`, `heightMeters`, `leanBodyMassKilograms`, `bodyTemperatureCelsius`, `oxygenSaturationPercent`, `bloodGlucoseMilligramsPerDeciliter`, `bloodPressureSystolicMillimetersOfMercury`, `bloodPressureDiastolicMillimetersOfMercury` |
| `NutritionEntry` | `start: Date`, `end: Date`, `name?`, `nutrients: Nutrients`. Every `Nutrients` field is optional and carries its unit in its name, such as `energyKilocalories`, `proteinGrams`, `sodiumMilligrams` and `vitaminDMicrograms`                                                                                   |

A `BodyEntry` with blood pressure needs both halves, or the call rejects with `blood_pressure_incomplete`.

### HealthChange

```typescript
type HealthChange = { category: DataCategory; day: string };
```

It carries no health value. Read the day again through the same namespace.

### PlannedWorkout

```typescript
type PlannedWorkout = {
  id: string;                  // Terra's plan ID
  plannedOn: string;           // the day the plan is for
  activity: WorkoutActivity;   // the workout type
  title?: string;              // the plan's name
  completedAt?: Date;          // when it was completed
};
```

### WorkoutSchedulingStatus

| Value           | Meaning                                                    |
| --------------- | ---------------------------------------------------------- |
| `unsupported`   | Below iOS 17, or WorkoutKit cannot schedule on this device |
| `notDetermined` | Not asked yet                                              |
| `denied`        | The person refused                                         |
| `authorized`    | Plans are put on the Watch on every sync run               |

### DiagnosticsState

| `state`                        | Extra fields  | Meaning                                                                                                                                                                           |
| ------------------------------ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `healthy`                      |               | Delivering normally                                                                                                                                                               |
| `quiet`                        | `since: Date` | No new data since `since`. Often a person who has not worn their watch                                                                                                            |
| `backgroundRestricted`         | `reason?`     | The platform limits background work. Android says why: `oemRestricted`, `backgroundReadDenied`, `healthConnectFeatureUnavailable`, `storeFeatureUnavailable` or `ticksNotRunning` |
| `backgroundRefreshUnscheduled` |               | No background wake is scheduled. On iOS, usually because the app's own refresh request holds the one pending request iOS allows. On Android, background sync was never registered |
| `pendingRetry`                 |               | A delivery failed and is queued for retry                                                                                                                                         |
| `linkRevoked`                  |               | Terra stopped accepting this device's key. Call `connect` again                                                                                                                   |
| `devIDMismatch`                |               | This device's stored state belongs to another dev ID                                                                                                                              |

### SupportReport

`sdkVersion`, `generatedAt: Date`, `state: DiagnosticsState`, `lastDelivery?: Date`, `isConnected`, `requestedCategories`, `requestedWrites`, `requestedWorkouts`, and `recentEvents: TerraEvent[]`.

### TerraEvent

An object with `at`, `event` (the kind, such as `uploadBatch` or `linkRevoked`) and the fields that kind carries.

In 2.3.0 and later, the kinds include `clinicalRecordTooLarge` (iOS only: a single clinical record over the upload size limit was skipped) and `devIDBindingChanged` (a multi-dev-ID customer's binding changed). A failure's code can be `workoutsRequired`, `dataTypeNotEnabled` (iOS only) or `linkRefused`.

### BootstrapState

```typescript
type BootstrapState = {
  bootstrapped: boolean;          // whether the native bootstrap ran
  devId?: string;                 // the dev ID the native side read
  platform: string;               // 'ios' or 'android'
  sdkVersion: string;             // the native SDK's version
  backgroundRegistered: boolean;  // whether background sync was registered at launch
  devIdMode?: string;             // 'single' or 'multiple', as the native bootstrap set it. 2.3.0 and later
};
```

### DevIdBinding

One customer linked to a [multi-dev-ID](#multi-dev-id-mode) installation. Available in 2.3.0 and later.

```typescript
type DevIdBinding = {
  devId: string;                 // the customer's dev ID
  userId: string;                // Terra's ID for this customer's connection
  dataTypes?: readonly string[]; // the upload routes the customer selected, as Terra answered at link
  linkedAt: Date;
  active: boolean;               // false once Terra no longer lists this connection
};
```

When `dataTypes` is absent, the app's requested access is synced for that customer. Nothing is read or backfilled for an inactive binding until the customer links again.

## Initialization

### createTerra

Attaches the JavaScript runtime to the native client your app built at launch, and returns the `Terra` client.

```typescript
function createTerra(options?: TerraOptions): Terra
```

* (Optional) `options: TerraOptions` ➡ The [token provider and its timeout](#terraoptions).

**returns** `Terra`: the client, with `permissions`, `diagnostics`, `background`, `body`, `daily`, `sleep`, `activity`, `nutrition`, `menstruation`, `linkedDevIds` and, on iOS, `athlete` and `plannedWorkouts`.

{% hint style="warning" %}
Call it once, at module scope. The native client outlives a JavaScript reload, so a reload attaches again rather than building a second client. Throws on a platform other than iOS or Android.
{% endhint %}

```typescript
export const terra = createTerra({ tokenProvider: () => api.terraToken() });
```

### attach

Describes the native client this runtime is attached to.

```typescript
attach(): Promise<BootstrapState>
```

**returns** `Promise<BootstrapState>`: rejects with `bridge.not_bootstrapped` when the app's native launch did not set Terra up. `details.line` names the line to add.

## Connection setup and management

### availability

Whether the device can serve `source` at all, and if not, why. Available in 2.2.1 and later.

```typescript
availability(source?: Source): Promise<StoreAvailability>
```

* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<StoreAvailability>`: [`StoreAvailability`](#storeavailability). iOS answers `available` or `unsupportedDevice`. Android answers the store's own reason, such as `providerAppMissing` when Health Connect needs installing.

It needs no connection and prompts for nothing, so call it before `connect` to decide whether to offer the link.

```typescript
const availability = await terra.availability();
if (availability.kind === 'providerAppMissing') showInstallHealthConnect();
```

### connect

Links `source` for the person `endUser` names, or restores the link already made for them. A restored link makes no network call.

```typescript
connect(source: Source, endUser: EndUser, options?: { token?: string }): Promise<Connection>
```

* `source: Source` ➡ The health store to link, `'health'` or `'samsungHealth'`.
* `endUser: EndUser` ➡ The person this link is for.
* (Optional) `options.token: string` ➡ A token already in hand, such as from a QR code. It always creates a fresh link. Without it, `tokenProvider` is asked, and only when a new link is needed.

**returns** `Promise<Connection>`: rejects with `token_unavailable` when a new link is needed and there is neither a token nor a `tokenProvider`, `token_rejected` when the token is expired or spent, and `dev_id_mismatch` when this device's stored state belongs to another dev ID.

```typescript
const connection = await terra.connect('health', EndUser.reference(user.id));
```

### connections

Returns the links on this device.

```typescript
connections(): Promise<readonly Connection[]>
```

**returns** `Promise<readonly Connection[]>`

### disconnect

Forgets the link on the device and tells Terra to stop accepting its key.

```typescript
disconnect(source?: Source): Promise<void>
```

* (Optional) `source: Source` ➡ The link to forget. Defaults to `'health'`.

**returns** `Promise<void>`

To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

## Permissions

### permissions.request

Shows one sheet for reads and writes, together with everything asked before.

```typescript
permissions.request(access: Partial<HealthAccess>, source?: Source): Promise<HealthAccess | undefined>
```

* `access: Partial<HealthAccess>` ➡ The categories to read and write, and in 2.3.0 and later the single types to read in `readTypes`. Leave out what you don't need.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<HealthAccess | undefined>`: on Android, what this call obtained. On iOS, `undefined`, because HealthKit does not report read grants.

```typescript
const granted = await terra.permissions.request({ read: ['activity', 'daily', 'sleep'] });
```

To ask for single types, pass `readTypes`. The sheet then names exactly those types, and the install becomes type-scoped. See [`HealthDataType`](#healthdatatype) for what that changes.

```typescript
await terra.permissions.request({
  readTypes: ['workouts', 'activeEnergy', 'distance', 'steps', 'heartRate', 'sleepAnalysis'],
});
```

`clinicalRecord` is ignored here, in either direction. Request it with [`permissions.requestClinicalRecords`](#permissions.requestclinicalrecords).

{% hint style="info" %}
On Android, `request` rejects with `bridge.no_activity` when no activity is on screen to present the sheet, and `bridge.permission_sheet_unavailable` when a sheet from an earlier request is still up. Both are retryable.
{% endhint %}

### permissions.status

Returns read access for one category.

```typescript
permissions.status(category: DataCategory, source?: Source): Promise<PermissionStatus>
```

* `category: DataCategory` ➡ The category to check.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<PermissionStatus>`

### permissions.typeStatus

Returns read access for one [`HealthDataType`](#healthdatatype). Available in 2.3.0 and later.

```typescript
permissions.typeStatus(type: HealthDataType, source?: Source): Promise<PermissionStatus>
```

* `type: HealthDataType` ➡ The type to check.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<PermissionStatus>`:

* iOS answers `notDisclosed` wherever it has the type, because HealthKit never reports a read decision.
* Android answers `granted` once any permission behind the type is granted, `denied` when it was asked for, by type or through a category, and nothing behind it is granted, and `notDetermined` when it was never asked for. `workouts` is granted by the exercise permission alone.
* A type the platform has no store type for rejects with `bridge.unsupported_on_platform`.

```typescript
const status = await terra.permissions.typeStatus('heartRate');
```

### permissions.writeStatus

Returns write access for one category.

```typescript
permissions.writeStatus(category: DataCategory, source?: Source): Promise<PermissionStatus>
```

* `category: DataCategory` ➡ The category to check.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<PermissionStatus>`

### permissions.requested

Returns everything requested so far.

```typescript
permissions.requested(source?: Source): Promise<HealthAccess>
```

* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<HealthAccess>`

## Data retrieval

The SDK reads the device's own store. Reads return the platform's raw samples, not Terra's normalised payloads; Terra's payloads arrive at your data destination.

A read rejects with `not_connected` before `connect`, and with `authorization_not_determined` for a category your app never requested. On Android it rejects with `permission_denied`, naming the category in `details.category`, when the person refused the grant.

### body.heartRate

```typescript
body.heartRate(range: TimeRange): Promise<readonly HeartRateSample[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly HeartRateSample[]>`: heart rate samples in the range.

```typescript
const hr = await terra.body.heartRate({ kind: 'lastHours', hours: 1 });
```

### body.restingHeartRate

The store's own resting heart rate, one per day it computed, never derived from heart rate readings. Available in 2.2.1 and later.

```typescript
body.restingHeartRate(range: TimeRange): Promise<readonly RestingHeartRateSample[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly RestingHeartRateSample[]>`: resting heart rate in the range.

On Android, Health Connect grants resting heart rate under `daily`, so request `daily` as well as `body`. An app that requested only `body` gets `authorization_not_determined`.

```typescript
const resting = await terra.body.restingHeartRate({ kind: 'lastDays', days: 7 });
```

### body.readings

Weight, height, BMI (iOS), body fat, lean mass, heart rate variability, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate. Available in 2.2.1 and later.

```typescript
body.readings(range: TimeRange): Promise<readonly BodyReading[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly BodyReading[]>`: body readings in the range. Each reading's [`kind`](#bodyreadingkind) says what it measured and fixes the unit.

```typescript
const readings = await terra.body.readings({ kind: 'lastDays', days: 30 });
const weights = readings.filter((r) => r.kind.type === 'measurement' && r.kind.metric === 'weight');
```

### daily.steps

```typescript
daily.steps(range: TimeRange): Promise<readonly StepCount[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly StepCount[]>`: step totals in the range.

### daily.totals

The store's own total for each whole local day the range touches. Available in 2.2.1 and later.

```typescript
daily.totals(range: TimeRange): Promise<readonly DayTotal[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly DayTotal[]>`: one total per metric per day: distance, active and basal energy, flights climbed and, on iOS, exercise minutes.

* A day the range covers only in part is still that day's whole total.
* A day with nothing recorded has no total, not a zero.
* Steps are not included. Read them with [`daily.steps`](#daily.steps), which keeps writers apart.
* Android's Health Connect does not split distance by activity, so it answers `distanceWalkingRunning` only.

```typescript
const totals = await terra.daily.totals({ kind: 'lastDays', days: 7 });
const energy = totals.filter((t) => t.metric === 'activeEnergyBurned');
```

### daily.intraday

The active energy, basal energy (iOS), distance and floors records the day totals are made of. Available in 2.2.1 and later.

```typescript
daily.intraday(range: TimeRange): Promise<readonly IntradaySample[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly IntradaySample[]>`: the records in the range, as the store holds them. A record that crosses midnight is returned whole.

```typescript
const samples = await terra.daily.intraday({ kind: 'today' });
```

### sleep.segments

```typescript
sleep.segments(range: TimeRange): Promise<readonly SleepSegment[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly SleepSegment[]>`: sleep stages in the range.

### activity.workouts

```typescript
activity.workouts(range: TimeRange): Promise<readonly Workout[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly Workout[]>`: workouts in the range.

### activity.routes

The GPS tracks of the workouts in the range. Available in 2.2.1 and later.

```typescript
activity.routes(range: TimeRange): Promise<readonly WorkoutRoute[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly WorkoutRoute[]>`: one route per workout that recorded one, each naming its workout by `workoutId`.

```typescript
const routes = await terra.activity.routes({ kind: 'lastDays', days: 1 });
const routeFor = (workoutId: string) => routes.find((r) => r.workoutId === workoutId);
```

### activity.intensity

Speed, power and cycling cadence readings in the range. Available in 2.2.1 and later.

```typescript
activity.intensity(range: TimeRange): Promise<readonly WorkoutIntensitySample[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly WorkoutIntensitySample[]>`: the readings in the range. iOS names each one's workout in `workoutId`. Health Connect stores them apart from any session, so on Android `workoutId` is absent and `start` equals `end`.

```typescript
const power = (await terra.activity.intensity({ kind: 'lastDays', days: 1 })).filter((s) => s.metric === 'power');
```

### nutrition.quantities

One quantity per nutrient a meal recorded in the range, not grouped into meals. Available in 2.2.1 and later.

```typescript
nutrition.quantities(range: TimeRange): Promise<readonly DietaryQuantity[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly DietaryQuantity[]>`: the quantities in the range. Quantities of one meal share `foodCorrelationId`. Water is not among them: read it with [`nutrition.hydration`](#nutrition.hydration).

```typescript
const quantities = await terra.nutrition.quantities({ kind: 'lastDays', days: 7 });
```

### nutrition.hydration

Water drunk in the range, one sample per drink. Available in 2.2.1 and later.

```typescript
nutrition.hydration(range: TimeRange): Promise<readonly HydrationSample[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly HydrationSample[]>`: the drinks in the range, in millilitres.

```typescript
const drinks = await terra.nutrition.hydration({ kind: 'today' });
```

### menstruation.flow

Logged flow days overlapping the range. Available in 2.2.1 and later.

```typescript
menstruation.flow(range: TimeRange): Promise<readonly MenstruationFlowDay[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly MenstruationFlowDay[]>`: one per logged day, each bounded by that day's local midnights. On iOS a day logged with no flow is returned with `flow: 'none'`, not left out.

```typescript
const days = await terra.menstruation.flow({ kind: 'lastDays', days: 90 });
```

### menstruation.events

Ovulation tests, cervical mucus and intermenstrual bleeding logged in the range. Available in 2.2.1 and later.

```typescript
menstruation.events(range: TimeRange): Promise<readonly MenstrualEvent[]>
```

* `range: TimeRange` ➡ The window to read.

**returns** `Promise<readonly MenstrualEvent[]>`: the events in the range, each at the instant it was logged.

```typescript
const events = await terra.menstruation.events({ kind: 'lastDays', days: 90 });
```

### changes

Each of `body`, `daily`, `sleep` and `activity` reports the days whose data changed.

```typescript
changes(listener: (change: HealthChange) => void, onError?: (error: TerraError) => void): Unsubscribe
```

* `listener` ➡ Called with a [`HealthChange`](#healthchange) for each changed day.
* (Optional) `onError` ➡ Called when the stream fails.

**returns** `Unsubscribe`: call it to stop.

```typescript
const stop = terra.sleep.changes(({ category, day }) => refreshSleep(day));
stop();
```

## Writing data

### log

Each of `body`, `daily`, `sleep`, `activity` and `nutrition` writes its own entry type. `body` also has `logHeartRate`.

```typescript
body.log(entries: readonly BodyEntry[]): Promise<readonly string[]>
body.logHeartRate(entries: readonly HeartRateEntry[]): Promise<readonly string[]>
daily.log(entries: readonly StepEntry[]): Promise<readonly string[]>
sleep.log(entries: readonly SleepEntry[]): Promise<readonly string[]>
activity.log(entries: readonly WorkoutEntry[]): Promise<readonly string[]>
nutrition.log(entries: readonly NutritionEntry[]): Promise<readonly string[]>
```

* `entries` ➡ The [entries](#entries) to write.

**returns** `Promise<readonly string[]>`: the IDs written. A `log` that fails partway rejects with `rollback_incomplete` when the samples already written could not be removed.

```typescript
await terra.nutrition.log([
  { start: new Date(), end: new Date(), name: 'Lunch', nutrients: { energyKilocalories: 640, proteinGrams: 32 } },
]);
```

{% hint style="info" %}
Nutrition is write only, on both platforms.
{% endhint %}

### delete

Each of `body`, `daily`, `sleep`, `activity` and `nutrition` deletes a sample your app wrote.

```typescript
delete(id: string): Promise<void>
```

* `id: string` ➡ The ID `log` returned.

**returns** `Promise<void>`: rejects with `sample_not_found` when the ID is not your app's to remove.

## Background sync

### background.isRegistered

Whether the native bootstrap registered background sync at launch.

```typescript
background.isRegistered(): Promise<boolean>
```

**returns** `Promise<boolean>`: `false` is a setup problem.

{% hint style="info" %}
There is no call that starts a sync. The SDK uploads after a permission grant, after a new link, when the app comes to the foreground, and on background runs.
{% endhint %}

## Diagnostics

### diagnostics.state

What the SDK believes about delivery right now.

```typescript
diagnostics.state(source?: Source): Promise<DiagnosticsState>
```

* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<DiagnosticsState>`

### diagnostics.lastDelivery

When data last reached Terra.

```typescript
diagnostics.lastDelivery(source?: Source): Promise<Date | undefined>
```

**returns** `Promise<Date | undefined>`

### diagnostics.report

A redacted report of the device's state.

```typescript
diagnostics.report(source?: Source): Promise<SupportReport>
```

**returns** `Promise<SupportReport>`

### diagnostics.send

Sends that report to Terra support.

```typescript
diagnostics.send(source?: Source): Promise<void>
```

**returns** `Promise<void>`

### diagnostics.events

Everything the SDK does, as it happens. Never carries a health value.

```typescript
diagnostics.events(listener: (event: TerraEvent) => void, onError?: (error: TerraError) => void): Unsubscribe
```

* `listener` ➡ Called with each [`TerraEvent`](#terraevent).
* (Optional) `onError` ➡ Called when the stream fails.

**returns** `Unsubscribe`: call it to stop.

```typescript
const stop = terra.diagnostics.events((event) => console.log(event.event, event.at));
```

## Android-only methods

### permissions.statuses

Read access for every category in one call.

```typescript
permissions.statuses(source?: Source): Promise<Partial<Record<DataCategory, PermissionStatus>>>
```

**returns** `Promise<Partial<Record<DataCategory, PermissionStatus>>>`

### permissions.backgroundReadStatus

Health Connect's background read permission.

```typescript
permissions.backgroundReadStatus(source?: Source): Promise<PermissionStatus>
```

**returns** `Promise<PermissionStatus>`

### permissions.historyReadStatus

Health Connect's history read permission.

```typescript
permissions.historyReadStatus(source?: Source): Promise<PermissionStatus>
```

**returns** `Promise<PermissionStatus>`

### background.cancel

Drops the background schedule.

```typescript
background.cancel(): Promise<boolean>
```

**returns** `Promise<boolean>`

## iOS-only methods

`terra.plannedWorkouts`, `terra.athlete` and `terra.permissions.requestClinicalRecords` are `undefined` on Android. For planned workouts, see [Planned workouts on Apple Watch](https://docs.tryterra.co/mobile-sdks/planned-workouts-apple-watch).

### permissions.requestClinicalRecords

Asks for Apple Health Records (`clinicalRecord`) on HealthKit's own Health Records sheet. Available in 2.3.0 and later.

```typescript
permissions.requestClinicalRecords?: () => Promise<void>
```

**returns** `Promise<void>`: rejects with `health_records_unavailable` where the device has no Health Records, and with `health_records_usage_description_missing` when either Info.plist string below is missing.

Health Records are opt-in. Before you call it:

* Have Health Records (`CLINICAL_RECORD`) enabled for your Terra client. Until then, Terra refuses the uploads with `data_type_not_enabled`, and the SDK holds the data and stops reading it for a day at a time.
* Add `health-records` to the `com.apple.developer.healthkit.access` entitlement.
* Add `NSHealthShareUsageDescription` and `NSHealthClinicalHealthRecordsShareUsageDescription` to your Info.plist.

Clinical records go to Terra only. No local read returns them. iOS 16.4 added clinical notes, so call this again after the person upgrades from an earlier version. It shows a sheet only for what is new.

```typescript
await terra.permissions.requestClinicalRecords?.();
```

### plannedWorkouts.planned

The plans Terra holds for this person.

```typescript
plannedWorkouts.planned(): Promise<readonly PlannedWorkout[]>
```

**returns** `Promise<readonly PlannedWorkout[]>`

### plannedWorkouts.markComplete

Marks a plan complete.

```typescript
plannedWorkouts.markComplete(id: string, at?: Date): Promise<void>
```

* `id: string` ➡ The plan's ID.
* (Optional) `at: Date` ➡ When it was completed. Defaults to now.

**returns** `Promise<void>`

### plannedWorkouts.delete

Deletes a plan.

```typescript
plannedWorkouts.delete(id: string): Promise<void>
```

* `id: string` ➡ The plan's ID.

**returns** `Promise<void>`

### plannedWorkouts.schedulingStatus

Whether plans can be put on the person's Apple Watch. Never prompts.

```typescript
plannedWorkouts.schedulingStatus(): Promise<WorkoutSchedulingStatus>
```

**returns** `Promise<WorkoutSchedulingStatus>`

### plannedWorkouts.requestScheduling

Shows WorkoutKit's sheet if the person has not been asked. Once authorized, every sync run keeps the Watch schedule in step with Terra.

```typescript
plannedWorkouts.requestScheduling(): Promise<WorkoutSchedulingStatus>
```

**returns** `Promise<WorkoutSchedulingStatus>`

```typescript
if (terra.plannedWorkouts && (await terra.plannedWorkouts.schedulingStatus()) === 'notDetermined') {
  await terra.plannedWorkouts.requestScheduling();
}
```

{% hint style="info" %}
A planned workout call with an empty ID rejects with `planned_workout_unnamed`.
{% endhint %}

### athlete.profile

HealthKit's characteristics as one snapshot. Available in 2.2.1 and later.

```typescript
athlete.profile(): Promise<AthleteProfile | undefined>
```

It takes no range, because characteristics have no history. Request `'athlete'` first: without it HealthKit hides the characteristics.

**returns** `Promise<AthleteProfile | undefined>`: the profile. A characteristic with no value is absent, except `biologicalSex`, which is `'notSet'`. `undefined` only where the store has no characteristics at all.

```typescript
const profile = await terra.athlete?.profile();
```

## Multi-dev-ID mode

For a connector app that several Terra customers link the same person through. The installation keeps one store read, one upload and one device key for every linked customer, and each customer receives only the data types it selected. Most apps never use this. Available in 2.3.0 and later.

Turn it on in the native configuration. Until you do, every `linkedDevIds` call rejects with `dev_id_mismatch`:

* iOS: `TerraDevIDMode` set to `multiple` in your Info.plist.
* Android: `co.tryterra.sdk.DEV_ID_MODE` set to `multiple` in the application meta-data of your manifest.

[`attach()`](#attach) answers the mode in `devIdMode`, so you can check it before linking. In this mode `connect` is refused: link each customer with `linkedDevIds.link`.

### linkedDevIds.link

Links one customer's connection with a link token that customer's backend minted.

```typescript
linkedDevIds.link(devId: string, token: string, source?: Source): Promise<DevIdBinding>
```

* `devId: string` ➡ The customer's dev ID.
* `token: string` ➡ An auth token that customer minted.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<DevIdBinding>`: the customer's [binding](#devidbinding). The first customer links the installation. Every later one joins it and is sent the history the others already have. Rejects with `link_refused` when Terra will not share the device key with this customer, with Terra's reason in `details.reason`. A retry does not change that answer.

### linkedDevIds.unlink

Stops delivering to one customer and leaves the others linked.

```typescript
linkedDevIds.unlink(devId: string, source?: Source): Promise<void>
```

* `devId: string` ➡ The customer's dev ID.
* (Optional) `source: Source` ➡ Defaults to `'health'`.

**returns** `Promise<void>`. The last customer's unlink disconnects the installation.

### linkedDevIds.all

The customers linked to this installation.

```typescript
linkedDevIds.all(options?: { source?: Source; refresh?: boolean }): Promise<readonly DevIdBinding[]>
```

* (Optional) `options.source: Source` ➡ Defaults to `'health'`.
* (Optional) `options.refresh: boolean` ➡ Asks Terra first, so `active` is current.

**returns** `Promise<readonly DevIdBinding[]>`: in the order they linked, inactive ones included. The `devIDBindingChanged` event reports each change.

## Errors

### TerraError

```typescript
class TerraError extends Error {
  readonly code: TerraErrorCode;
  readonly retryable: boolean;
  readonly source: Source | undefined;
  readonly details: Record<string, unknown> | undefined;
  static from(thrown: unknown): TerraError;
}
```

* `code` ➡ A stable code from the table below. Switch on it.
* `retryable` ➡ Whether the same call could succeed if repeated. Read this rather than the table, because `network.server_error` decides per instance.
* `source` ➡ The source the failure is about, when there is one.
* `details` ➡ Extra context, such as `line` for `bridge.not_bootstrapped` and `op` or `path` for `bridge.invalid_payload`.
* `from(thrown)` ➡ Turns any rejection into a `TerraError`. A code the package does not know becomes `platform`, with the original in `details.unrecognisedCode`.

```typescript
try {
  await terra.connect('health', EndUser.reference(user.id));
} catch (e) {
  const error = TerraError.from(e);
  if (error.retryable) scheduleRetry();
}
```

### Error codes

| Code                                       | Retryable    | Platform     | Meaning                                                                                                                                                                |
| ------------------------------------------ | ------------ | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `health_data_unavailable`                  | No           | iOS, Android | The device cannot serve health data, or `samsungHealth` was asked for without the add-on                                                                               |
| `not_connected`                            | No           | iOS, Android | A call arrived before `connect`                                                                                                                                        |
| `route_awaiting_converter`                 | No           | iOS, Android | Terra cannot convert this data type yet, so the SDK does not send it                                                                                                   |
| `data_type_not_enabled`                    | No           | iOS          | Terra refused an upload because your Terra client has not enabled the data type. Only `clinicalRecord` needs enabling. The SDK holds the data and reports it as a skip |
| `token_unavailable`                        | No           | iOS, Android | `connect` needed a token and had neither a token nor a `tokenProvider`                                                                                                 |
| `token_rejected`                           | No           | iOS, Android | The token was expired, already spent or unknown                                                                                                                        |
| `token_provider_failed`                    | No           | iOS, Android | Your `tokenProvider` rejected                                                                                                                                          |
| `user_limit_reached`                       | No           | iOS, Android | Your plan's user allowance is used up                                                                                                                                  |
| `upgrade_required`                         | No           | iOS, Android | Terra has withdrawn this SDK version. Prompt an app update                                                                                                             |
| `platform`                                 | No           | iOS, Android | The OS refused for a reason the SDK does not classify                                                                                                                  |
| `device_key_unavailable`                   | No           | iOS, Android | The device's signing key could not be created, read or removed                                                                                                         |
| `signature_rejected`                       | No           | iOS, Android | Terra refused the signature on a signed call                                                                                                                           |
| `clock_skewed`                             | No           | iOS, Android | The device's clock is too far from Terra's. Only correcting the clock fixes it                                                                                         |
| `link_revoked`                             | No           | iOS, Android | Terra stopped accepting this device's key. Only a fresh link clears it                                                                                                 |
| `dev_id_mismatch`                          | No           | iOS, Android | This device's stored state belongs to a different dev ID                                                                                                               |
| `link_conflict`                            | Yes          | iOS, Android | Two requests raced for the same link and this one lost                                                                                                                 |
| `link_refused`                             | No           | iOS, Android | Multi-dev-ID mode only. Terra will not share the device key with this customer. `details.reason` carries Terra's reason                                                |
| `sync_already_running`                     | No           | iOS, Android | A sync for this data type is already running                                                                                                                           |
| `link_already_running`                     | No           | iOS, Android | A link for this source is already in progress                                                                                                                          |
| `store_locked`                             | Yes          | iOS, Android | The device has not been unlocked since it booted. Clears on unlock                                                                                                     |
| `store_unreadable`                         | No           | iOS, Android | Stored state could not be decoded and was dropped                                                                                                                      |
| `deadline_exceeded`                        | Yes          | iOS, Android | A run ran out of time before sending a batch. The next run continues                                                                                                   |
| `read_quota_exceeded`                      | Yes          | Android      | Health Connect's read quota for your app is spent. On Android 14 and later it refills within 15 minutes                                                                |
| `permission_denied`                        | No           | iOS, Android | Access was refused. On iOS, only writes report it                                                                                                                      |
| `authorization_not_determined`             | No           | iOS, Android | A read of a category your app never requested                                                                                                                          |
| `sample_not_found`                         | No           | iOS, Android | A delete named a sample that is not your app's to remove                                                                                                               |
| `rollback_incomplete`                      | No           | iOS, Android | A `log` failed partway and the samples already written could not be removed                                                                                            |
| `distance_not_attributable`                | No           | iOS          | A workout carried a distance for an activity with no distance type                                                                                                     |
| `workouts_required`                        | No           | iOS, Android | A request named `workoutRoute`, `speed`, `power` or `cyclingCadence` without `workouts` or `activity`. `details.type` names the type                                   |
| `blood_pressure_incomplete`                | No           | iOS, Android | A `BodyEntry` carried only one half of a blood pressure                                                                                                                |
| `authorization_unavailable_in_extension`   | No           | iOS          | A permission sheet was requested from an app extension                                                                                                                 |
| `health_records_unavailable`               | No           | iOS          | The device has no Health Records, for example in a region without them                                                                                                 |
| `health_records_usage_description_missing` | No           | iOS          | `NSHealthShareUsageDescription` or `NSHealthClinicalHealthRecordsShareUsageDescription` is missing from Info.plist                                                     |
| `planned_workout_unnamed`                  | No           | iOS          | A planned workout call had an empty ID                                                                                                                                 |
| `network.transport`                        | Yes          | iOS, Android | No HTTP response at all, such as a refused connection                                                                                                                  |
| `network.throttled`                        | Yes          | iOS, Android | Terra answered 429                                                                                                                                                     |
| `network.server_error`                     | Per instance | iOS, Android | Terra returned a status the SDK could not act on. Retryable for 5xx and 429                                                                                            |
| `network.malformed_response`               | No           | iOS, Android | A response the SDK could not read                                                                                                                                      |
| `network.offline`                          | Yes          | iOS          | The device is offline. Android reports `network.transport`                                                                                                             |
| `network.timed_out`                        | Yes          | iOS          | The request timed out. Android reports `network.transport`                                                                                                             |
| `bridge.not_bootstrapped`                  | No           | Both         | The native bootstrap did not run. `details.line` names the line to add                                                                                                 |
| `bridge.unsupported_on_platform`           | No           | Both         | This platform's SDK has no entry point for the call yet                                                                                                                |
| `bridge.no_activity`                       | Yes          | Android      | No activity was on screen to present a permission sheet                                                                                                                |
| `bridge.permission_sheet_unavailable`      | Yes          | Android      | A sheet from an earlier request is still up                                                                                                                            |
| `bridge.token_timeout`                     | No           | iOS          | `tokenProvider` did not answer within `tokenTimeoutMs`. Android reports `token_provider_failed`                                                                        |
| `bridge.invalid_payload`                   | No           | Both         | A request or response did not match its type. `details.op` names the call when JavaScript rejected it, and `details.path` names the field when the native side did     |

The package also exports the table as data: `retryableByCode`, `bridgeOwnedCodes` and `platformOnlyCodes`.

## Low-level exports

Most apps need only `createTerra`, `EndUser` and `TerraError`. The package also exports the layer `Terra` is built on, for wrappers and tests: `GeneratedClient`, `opIds`, `streamIds`, `availableOn`, `streamAvailableOn`, `eventKinds`, `decodeStreamDelivery`, `decodeStreamElement`, and every generated type.
