---
name: upflux-ota
description: >-
  Integrate Upflux Over-The-Air (OTA) updates into React Native (bare), Expo
  (expo-updates Protocol v1), or Capacitor mobile apps. Use this skill whenever
  the user asks to integrate Upflux, set up OTA updates, configure upflux.json
  or Expo updates, wire UpfluxModule in MainApplication or AppDelegate, or add
  Upflux.init() lifecycle callbacks.
---

# Upflux OTA Integration Skill

Follow these steps in order to integrate Upflux OTA updates into the user's mobile project.

---

## Step 1: Detect Project Platform & Architecture

Inspect `package.json`, `app.json`, and native directories before writing any code:

1. **Expo** — `package.json` depends on `expo` AND `app.json` (or `app.config.js` / `app.config.ts`) has an `"expo"` root key (without custom bare `UpfluxModule` wiring) -> Follow **Path B (Expo)**.
2. **Capacitor** — `package.json` depends on `@capacitor/core` or `capacitor.config.*` exists -> Follow **Path C (Capacitor)**.
3. **React Native (Bare)** — `package.json` depends on `react-native` with `android/` and `ios/` directories -> Follow **Path A (React Native Bare)**.
   - Check `react-native` version in `package.json` (`>= 0.73` uses `ReactHost` / `getDefaultReactHost`; `< 0.73` uses `ReactNativeHost.getJSBundleFile`).
   - Check Android entry file: `MainApplication.kt` vs `MainApplication.java`.
   - Check iOS entry file: `AppDelegate.mm` / `AppDelegate.m` vs `AppDelegate.swift`.

---

## Step 2: Gather Required Credentials

Check if `upflux.json` (React Native / Capacitor) or `app.json` `expo.updates` (Expo) already exists.
If missing, ask the user for:
- **`appId`**: Upflux Application ID from the Upflux Dashboard (required for React Native & Capacitor).
- **`clientKey`**: Read-only deployment Client Key (`upx_cli_...`) for `production` (and optionally `staging` / `development`).
- **`runtimeVersion`**: Semver matching the native binary version in `package.json` / `app.json` (default `"1.0.0"`).

> **Security Rule**: Only place `upx_cli_*` client keys in `upflux.json` or `app.json`. Never commit `upx_pub_*` publish keys into app source.

Alternatively, the user can scaffold config interactively via:
```bash
npx @upfluxhq/cli init
```

---

## Step 3: Platform-Specific Integration

### Path A: React Native (Bare) — `@upfluxhq/react-native`

#### A1. Install SDK & Pods
Detect the workspace package manager (`pnpm-lock.yaml`, `yarn.lock`, `package-lock.json`, or `bun.lockb`) and install `@upfluxhq/react-native`:
```bash
npm install @upfluxhq/react-native
cd ios && pod install
```

#### A2. Configure Android (`MainApplication`)

**React Native 0.73+ (`MainApplication.kt` with `ReactHost`):**
```kotlin
import com.upflux.UpfluxModule

class MainApplication : Application(), ReactApplication {

  override val reactHost: ReactHost by lazy {
    val customBundlePath = UpfluxModule.getJSBundleFile(this)
    getDefaultReactHost(
      context = applicationContext,
      packageList = PackageList(this).packages,
      jsBundleFilePath = customBundlePath
    )
  }
}
```
*(If the file also defines `reactNativeHost: ReactNativeHost`, override `getJSBundleFile()` inside it as well.)*

**React Native < 0.73 (`MainApplication.kt` with `ReactNativeHost`):**
```kotlin
import com.upflux.UpfluxModule

override fun getJSBundleFile(): String? {
    return UpfluxModule.getJSBundleFile(this@MainApplication) ?: super.getJSBundleFile()
}
```

**Java (`MainApplication.java`):**
```java
import com.upflux.UpfluxModule;

@Override
protected String getJSBundleFile() {
    String customBundle = UpfluxModule.getJSBundleFile(this);
    return customBundle != null ? customBundle : super.getJSBundleFile();
}
```

#### A3. Configure iOS (`AppDelegate`)

**Objective-C / Objective-C++ (`AppDelegate.mm` or `AppDelegate.m`):**
```objc
#import <upflux_react_native/UpfluxModule.h>

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
  return [self bundleURL];
}

- (NSURL *)bundleURL
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
  NSURL *customBundle = [UpfluxModule bundleURL];
  return customBundle ?: [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
```

**Swift (`AppDelegate.swift`):**
1. Add `#import <upflux_react_native/UpfluxModule.h>` to `<AppName>-Bridging-Header.h`.
2. In `AppDelegate.swift`:
```swift
override func bundleURL() -> URL? {
#if DEBUG
  return RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
  return UpfluxModule.bundleURL() ?? Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
```

#### A4. Create `upflux.json` at Project Root
```json
{
  "version": 1,
  "app": {
    "id": "<YOUR_APP_ID>",
    "runtimeVersion": "1.0.0",
    "serverUrl": "https://api.upflux.in"
  },
  "deployments": {
    "development": {
      "clientKey": "upx_cli_dev_xxxxx",
      "checkOnLaunch": "never",
      "installMode": "on_next_restart"
    },
    "production": {
      "clientKey": "upx_cli_prd_xxxxx",
      "checkOnLaunch": "always",
      "installMode": "on_next_restart"
    }
  }
}
```
> **Important (`installMode` choice)**:
> - Use `"installMode": "on_next_restart"` when showing custom download/staging UI (`onCheckComplete`, `onDownloadProgress`, `onUpdateQueued`) or when staging silently for next cold start.
> - Use `"installMode": "immediate"` only when the app should immediately reload the JS bundle as soon as download finishes (`onUpdateQueued` will not fire because `applyUpdate` reloads right away).

#### A5. Initialize SDK in Root Component (`App.tsx`)

**Option 1 — Silent Auto-Update (Zero UI):**
```tsx
import React, { useEffect } from 'react';
import { Upflux } from '@upfluxhq/react-native';

export default function App() {
  useEffect(() => {
    Upflux.init('production').catch((err) => {
      console.warn('[Upflux] Init failed:', err);
    });
  }, []);

  return <MainNavigator />;
}
```

**Option 2 — Custom Loader / Store Update Gate / Progress UI:**
Requires `"installMode": "on_next_restart"` in `upflux.json`:
```tsx
import React, { useEffect, useState } from 'react';
import { Upflux } from '@upfluxhq/react-native';

export default function App() {
  const [isCheckingUpdate, setIsCheckingUpdate] = useState(!__DEV__);
  const [isDownloading, setIsDownloading] = useState(false);
  const [downloadProgress, setDownloadProgress] = useState(0);

  useEffect(() => {
    Upflux.init('production', {
      onStoreUpdateRequired: ({ requiredBinaryVersion }) => {
        setIsCheckingUpdate(false);
        promptStoreUpdate(requiredBinaryVersion);
      },
      onCheckComplete: (hasUpdate) => {
        if (hasUpdate) {
          setIsDownloading(true);
        } else {
          setIsCheckingUpdate(false);
        }
      },
      onDownloadProgress: ({ percentage }) => setDownloadProgress(percentage),
      onUpdateQueued: (info) => {
        console.log(`[Upflux] Update ${info.releaseLabel} staged for next restart`);
        setIsDownloading(false);
        setIsCheckingUpdate(false);
      },
      onRollback: ({ rolledBackFrom, rolledBackTo }) => {
        console.warn(`[Upflux] Rolled back from ${rolledBackFrom} to ${rolledBackTo ?? 'binary'}`);
      },
      onError: (error) => {
        console.warn('[Upflux] Update error:', error.message);
        setIsDownloading(false);
        setIsCheckingUpdate(false);
      },
    }).catch((error) => {
      console.warn('[Upflux] Init failed:', error);
      setIsCheckingUpdate(false);
    });
  }, []);

  return <MainNavigator />;
}
```
> **Dev Mode Note**: In `__DEV__` (Metro bundler), `Upflux.init()` automatically skips background OTA network checks and resolves immediately, so initialize `isCheckingUpdate` to `!__DEV__` (or clear it inside `.then()`).

---

### Path B: Expo (`expo-updates` Protocol v1)

Upflux natively implements Expo Updates Protocol v1. No custom Upflux SDK package is needed—use standard `expo-updates`.

#### B1. Install `expo-updates`
```bash
npx expo install expo-updates
```

#### B2. Configure `app.json` / `app.config.js`
Set `runtimeVersion` and configure `expo.updates` with the Upflux endpoint and `x-client-key` header:
```json
{
  "expo": {
    "name": "MyApp",
    "slug": "my-app",
    "version": "1.0.0",
    "runtimeVersion": "1.0.0",
    "updates": {
      "enabled": true,
      "checkAutomatically": "ON_LOAD",
      "fallbackToCacheTimeout": 0,
      "enableBsdiffPatchSupport": true,
      "url": "https://api.upflux.in/api/updates/check",
      "requestHeaders": {
        "x-client-key": "upx_cli_prd_xxxxx"
      }
    }
  }
}
```

> Note: `"enableBsdiffPatchSupport": true` enables native `BSDIFF40` binary delta updates on Expo SDK 55+ (automatically ignored with full-bundle fallback on older SDKs or first launch).

#### B3. Optional Manual Update Check / Custom UI (`expo-updates`)
If the user wants custom update UI instead of silent startup checks:
1. Set `"checkAutomatically": "NEVER"` in `app.json`.
2. Use `Updates.useUpdates()` or imperative calls in the app:
```tsx
import * as Updates from 'expo-updates';

export async function checkAndApplyExpoUpdate() {
  if (__DEV__) return;
  try {
    const update = await Updates.checkForUpdateAsync();
    if (update.isAvailable) {
      await Updates.fetchUpdateAsync();
      await Updates.reloadAsync();
    }
  } catch (error) {
    console.warn('[Upflux] Expo update check failed:', error);
  }
}
```

---

### Path C: Capacitor — `@upfluxhq/capacitor`

#### C1. Install SDK & Sync Native Projects
No manual Android/iOS native file edits are required for Capacitor (5.x / 6.x):
```bash
npm install @upfluxhq/capacitor
npx cap sync
```

#### C2. Create `upflux.json` at Project Root
```json
{
  "version": 1,
  "app": {
    "id": "<YOUR_APP_ID>",
    "runtimeVersion": "1.0.0",
    "serverUrl": "https://api.upflux.in"
  },
  "deployments": {
    "development": {
      "clientKey": "upx_cli_dev_xxxxx",
      "checkOnLaunch": "never",
      "installMode": "on_next_restart"
    },
    "production": {
      "clientKey": "upx_cli_prd_xxxxx",
      "checkOnLaunch": "always",
      "installMode": "immediate"
    }
  }
}
```

#### C3. Initialize in Entry Point (`main.ts` / `index.tsx` / `App.tsx`)
Call `Upflux.init()` during app bootstrap:
```ts
import { Upflux } from '@upfluxhq/capacitor';

await Upflux.init('production', {
  onDownloadProgress: ({ percentage }) => {
    console.log(`[Upflux] Downloading update: ${percentage}%`);
  },
  onReadyToInstall: async (result) => {
    // Optional: prompt user before reloading WebView
    await result.apply();
  },
  onError: (error) => {
    console.warn('[Upflux] Update error:', error.message);
  },
});
```

---

## Step 4: Verification Checklist

Before finishing, verify:
1. **Config file valid**:
   - React Native / Capacitor: `upflux.json` exists at project root with valid JSON, `version: 1`, `app.id`, and `deployments.<profile>.clientKey`.
   - Expo: `app.json` has `expo.runtimeVersion`, `expo.updates.url: "https://api.upflux.in/api/updates/check"`, and `expo.updates.requestHeaders["x-client-key"]` (plus `enableBsdiffPatchSupport: true` for Expo SDK 55+ delta updates).
2. **Native wiring (React Native Bare only)**:
   - Android `MainApplication` imports `com.upflux.UpfluxModule` and passes `UpfluxModule.getJSBundleFile(this)` into `getDefaultReactHost` (RN 0.73+) or overrides `getJSBundleFile` (RN < 0.73).
   - iOS `AppDelegate` imports `<upflux_react_native/UpfluxModule.h>` and returns `[UpfluxModule bundleURL]` (or `UpfluxModule.bundleURL()` in Swift) in release builds (`#else` branch of `#if DEBUG`).
3. **Lifecycle consistency**:
   - If `onUpdateQueued` is used to dismiss a custom loader, confirm `installMode` in `upflux.json` is `"on_next_restart"` (not `"immediate"`).
4. **No secret leakage**:
   - Confirm no `upx_pub_*` publish key is stored in `upflux.json`, `app.json`, or client source code.

