# react-native-healkite

Healkite SDK for React Native 0.80+ (New Architecture, Hermes). iOS (Swift) + Android (Kotlin).

## 1. Install

```sh
npm install react-native-healkite && cd ios && pod install
```

## 2. Configure

| | iOS `Info.plist` | Android `res/values/strings.xml` |
|---|---|---|
| CDN base URL | `HealkiteCdnUrl` | `healkite_cdn_url` |
| Channel key | `HealkiteChannel` | `healkite_channel` |
| Runtime version (default: app version) | `HealkiteRuntimeVersion` | `healkite_runtime_version` |
| Your bundle-signing public key (recommended) | `HealkitePublicKey` | `healkite_public_key` |
| Server manifest key (recommended) | `HealkiteManifestKey` | `healkite_manifest_key` |
| Backup CDN, used when the primary fails (optional) | `HealkiteCdnFallbackUrl` | `healkite_cdn_fallback_url` |

Release builds should only use HTTPS CDN URLs. Never ship store builds pointing at staging
(`*.workers.dev`, `*.r2.dev`) URLs.

## Expo (SDK 50+)

No native code to edit: add the config plugin and rebuild (`npx expo prebuild` or an EAS Build).

```json
{
  "expo": {
    "plugins": [
      ["react-native-healkite", {
        "cdnUrl": "https://cdn.healkite.com",
        "channel": "production-…",
        "manifestKey": "MFkw…",
        "publicKey": "MFkw…"
      }]
    ]
  }
}
```

The plugin writes the config values, makes release builds load the OTA bundle (Android `ExpoReactHostFactory` /
`MainApplication`, iOS `AppDelegate`) and warns if `expo-updates` is also installed (use one or the other).
`healkite release` detects Expo and bundles with `expo export:embed`. Then continue with step 4 (Sync).

## 3. Load the OTA bundle (release builds)

**iOS** — in your `RCTDefaultReactNativeFactoryDelegate` (e.g. `SceneDelegate.swift`):

```swift
import Healkite

override func bundleURL() -> URL? {
  #if DEBUG
  RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
  #else
  HealkiteCore.bundleURL() ?? Bundle.main.url(forResource: "main", withExtension: "jsbundle")
  #endif
}
```

**Android** — in `MainApplication.kt`:

```kotlin
import dev.healkite.Healkite

getDefaultReactHost(
  context = applicationContext,
  packageList = PackageList(this).packages,
  jsBundleFilePath = if (BuildConfig.DEBUG) null else Healkite.getJSBundleFile(this),
)
```

## 4. Sync

```tsx
import Healkite, { KillSwitchGate } from "react-native-healkite";

export default function App() {
  useEffect(() => {
    // Confirms the running bundle is healthy (prevents auto-rollback), checks for updates,
    // installs (patch or full), sends telemetry. Never throws.
    Healkite.sync();
  }, []);
  return <KillSwitchGate>{/* your app */}</KillSwitchGate>;
}
```

Call `sync()` (or `notifyAppReady()`) **after your first screen renders**: a new bundle that never
gets there is rolled back automatically on the next launch.

| API | |
|---|---|
| `sync({ installMode? })` | One call: ready → check → install → (restart if mandatory/immediate) → telemetry |
| `checkForUpdate()` | `UPDATE_AVAILABLE` / `UP_TO_DATE` / `NOT_IN_ROLLOUT` / `SKIPPED_FAILED` / `ROLLBACK_TO_EMBEDDED` / `NO_RELEASE` |
| `notifyAppReady()` | Confirm the running bundle |
| `restart()` | Apply a staged update now |
| `getState()` | running / current / pending / failed / lastRollback / lastInstallMethod |
| `<HealkiteVersion />`, `useVersionInfo()`, `getVersionInfo()` | Show the app version and the running update ("2.4.0 (112) · v12") |
| `setHints(false)` | Turn off the feature tips logged in development builds (JS console / device log) |
| `getKillSwitch()`, `useKillSwitch()`, `<KillSwitchGate fallback?>` | Maintenance mode |
| `flushEvents()` | Send queued telemetry now (sync does this) |

## Instant hotfix (silent push, optional)

Normally devices pick up updates on their next launch. Connect Firebase (dashboard → Settings → Instant updates)
and Healkite sends one silent message to a topic per app version when you ship with `--hotfix` or press
**Push now**; open and background apps update within seconds.

```js
import messaging from "@react-native-firebase/messaging";
import Healkite from "react-native-healkite";

messaging().subscribeToTopic(Healkite.getPushTopic());
messaging().setBackgroundMessageHandler((m) => Healkite.handlePush(m.data));
messaging().onMessage((m) => Healkite.handlePush(m.data));
```

`handlePush` returns `false` for messages that aren't from Healkite, so it can sit in front of your own handlers.
iOS needs the Background Modes → Remote notifications capability.

## PR previews on the store build (optional)

Testers open a link (or scan a QR code) and the app they installed from the store switches to a pull
request's code, with a banner to exit. Set your app's URL scheme in the dashboard (Settings → PR previews),
then pass incoming links to Healkite and render the banner:

```tsx
import { Linking } from "react-native";
import Healkite, { PreviewBanner } from "react-native-healkite";

Linking.addEventListener("url", ({ url }) => Healkite.openPreview(url)); // false for other links
Linking.getInitialURL().then((url) => url && Healkite.openPreview(url));

export default function App() {
  return (
    <>
      {/* your app */}
      <PreviewBanner />
    </>
  );
}
```

Publish previews from CI with the GitHub Action (`mode: preview`, and `preview-close` when the PR closes) or
`npx healkite preview --from <channel-key> --name pr-123 -p android -r 1.0`. A preview ends automatically on
devices when it's closed, and a new store build always starts on its normal channel.

## Testing your app

```js
jest.mock("react-native-healkite", () => require("react-native-healkite/jest/mock"));
```

## How updates are applied

1. Manifest fetched (revalidated, CDN-cached) and its server signature verified.
2. Device decides rollout locally: `fnv1a32(salt:deviceId) % 100 < pct`.
3. Bundle signature verified **before** downloading; patch preferred when one exists for the running
   bundle, full download otherwise (and as fallback).
4. Every file checked against its sha256; unpacked into the app's support directory.
5. Next launch runs it as a trial; `notifyAppReady()` promotes it. A crash before that rolls back and
   marks the bundle as failed so it is never retried.
6. A new store binary always starts from its embedded bundle.

## License

MIT. The SDK is open source so you can audit exactly what runs in your app.
