8000 GitHub - klehmann/react-native-automerge-generated · GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

react-native-automerge-generated

Native Automerge bindings for React Native via compiled Rust + UniFFI.

Replaces the WebAssembly-based Automerge backend with a native Rust implementation exposed through JSI, enabling:

  • Hermes support — no longer requires JSC for WebAssembly
  • Android support — WASM-based automerge only worked reliably on iOS
  • No JSC patches — eliminates the createArrayBuffer patch for JSCRuntime.cpp
  • No Metro hacks — no more slim→fullfat resolver redirects
  • Better performance — direct native calls via JSI instead of WASM interpretation
  • Drop-in replacement — compatible with existing @automerge/automerge code

Architecture

App TypeScript
       │
       ├─────────────────────────────────────┐
       │                                     │
   Automerge API                    @automerge/automerge/slim
   (WASM-compatible)                    + UseApi(nativeApi)
       │                                     │
       └─────────────────────────────────────┤
                                             │
proxy.ts  (custom proxy system)              │
       │                                     │
useapi-adapter.ts  (type conversion + API bridge)
       │
src/generated/automerge.ts  (auto-generated by ubrn)
       │  JSI (C++)
cpp/generated/  (auto-generated by ubrn)
       │  FFI (C ABI)
uniffi_automerge Rust crate  (UniFFI 0.29)
       │
automerge core (v0.7.3)

Hand-written components:

  1. rust/ — UniFFI-annotated Rust wrapper (ported from automerge-swift)
  2. src/useapi-adapter.ts — bridges generated API to @automerge/automerge/slim
  3. src/proxy.ts — custom proxy system for WASM-compatible API (no WASM dependencies)

Everything else (C++, ObjC++, Kotlin, generated TypeScript) is auto-generated by uniffi-bindgen-react-native.

Installation

npm install react-native-automerge-generated
# or
yarn add react-native-automerge-generated

iOS

cd ios && pod install

Android

Gradle sync should pick up the native module automatically.

Usage

This package provides two usage patterns. Both use the same native Rust backend.

Pattern A: Direct Automerge Import (Recommended)

Use the native implementation as a drop-in replacement for @automerge/automerge:

import { Automerge } from 'react-native-automerge-generated';

// Create and modify documents
let doc = Automerge.init();
doc = Automerge.change(doc, d => {
  d.tasks = [];
  d.tasks.push({ title: "Buy milk", done: false });
});

// Save and load
const saved = Automerge.save(doc);
const loaded = Automerge.load(saved);

// Merge documents
const doc1 = Automerge.change(doc, d => { d.title = "Version 1"; });
const doc2 = Automerge.change(doc, d => { d.title = "Version 2"; });
const merged = Automerge.merge(doc1, doc2);

// Access data as plain JavaScript objects
console.log(doc.tasks[0].title); // "Buy milk"

How it works:

  • The Automerge export provides a complete WASM-compatible API
  • Documents are returned as plain JavaScript objects that can be read directly
  • A custom proxy system intercepts writes during change() callbacks
  • No WASM dependencies — pure native implementation

TypeScript:

import { Automerge } from 'react-native-automerge-generated';
import type * as A from '@automerge/automerge';

// Use @automerge/automerge types
type Doc = A.Doc<{ title: string; tasks: Array<{ title: string; done: boolean }> }>;

let doc = Automerge.init<Doc>();
doc = Automerge.change(doc, d => {
  d.title = "My List";
  d.tasks = [];
});

Pattern B: UseApi Integration (Legacy)

Integrate the native backend with @automerge/automerge/slim:

import { UseApi } from '@automerge/automerge/slim';
import { nativeApi } from 'react-native-automerge-generated';

// Initialize once at app startup
UseApi(nativeApi);

// Then use automerge/slim normally
import * as Automerge from '@automerge/automerge/slim';

let doc = Automerge.init();
doc = Automerge.change(doc, d => {
  d.key = 'value';
});

Note: Pattern B requires @automerge/automerge as a dependency. Pattern A is self-contained.

Proxy System

The custom proxy system (Pattern A) provides a WASM-compatible API without any WASM dependencies:

// During change() callbacks, the document is wrapped in a proxy
Automerge.change(doc, d => {
  // Property assignments are intercepted
  d.name = "Alice";           // → doc.put('_root', 'name', 'Alice', 'str')
  d.items = [];               // → doc.putObject('_root', 'items', 'list')
  d.items.push("first");      // → doc.push(objId, 'first', 'str')

  // Nested objects work automatically
  d.user = { name: "Bob" };   // → creates nested map

  // Text objects are handled transparently
  d.notes = "Hello";          // → stored as Automerge.Text
});

// Outside change() callbacks, documents are plain JS objects
console.log(doc.name);        // "Alice"
console.log(doc.items[0]);    // "first"

The proxy system:

  • Intercepts property get/set operations
  • Translates assignments to native API calls (put(), insert(), delete())
  • Handles nested objects, arrays, and text automatically
  • Returns documents as plain JavaScript objects for reading

Type Mapping

The adapter converts between the generated API types and JavaScript types:

JavaScript Generated API Rust Type Conversion
ObjId (string "_root") ArrayBuffer Vec<u8> base64 with o: prefix
ChangeHash (hex string) ArrayBuffer [u8; 32] hex encode/decode
ActorId (hex string) ArrayBuffer Vec<u8> hex encode/decode
Cursor (string) ArrayBuffer Vec<u8> base64 with c: prefix
Uint8Array Array<number> Vec<u8> Array.from() / new Uint8Array()
JS primitives ScalarValue tagged union Rust enum tag-based dispatch
Objects/Arrays proxy during writes native doc get/put/insert/delete

Building from Source

Prerequisites

  • Rust toolchain (1.89+): rustup install stable
  • iOS targets: rustup target add aarch64-apple-ios aarch64-apple-ios-sim
  • Android targets: rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android
  • Android NDK (via Android Studio)
  • uniffi-bindgen-react-native: npm install (dev dependency)

Build

# iOS (builds universal static lib + generates bindings)
npm run build:ios

# Android (builds for all ABIs + generates bindings)
npm run build:android

# Check Rust compiles
cd rust && cargo check

Project Structure

rust/
  src/
    automerge.udl     UniFFI interface definition (50+ methods)
    doc.rs            Doc wrapper around automerge::AutoCommit
    sync_state.rs     SyncState wrapper
    scalar_value.rs   ScalarValue enum (String, Int, Uint, F64, etc.)
    value.rs          Value enum (Object | Scalar)
    patches.rs        Patch/PatchAction types
    obj_id.rs         ObjId custom type (ArrayBuffer)
    actor_id.rs       ActorId custom type (ArrayBuffer)
    change_hash.rs    ChangeHash custom type (ArrayBuffer)
    cursor.rs         Cursor custom type (ArrayBuffer)
    ...
  Cargo.toml
src/
  useapi-adapter.ts   UseApi bridge + Automerge API wrapper
  proxy.ts            Custom proxy system for WASM-compatible API
  generated/
    automerge.ts      Auto-generated TypeScript bindings
    automerge-ffi.ts  Auto-generated FFI layer
  index.ts            Package entry point

Current Limitations

  • Stubbed methods: unmark(), spans(), getBlock(), updateBlock(), saveBundle(), encodeChange() throw or return empty values. These are not needed for core automerge operations.
  • getChanges() returns concatenated bytes — the Rust encode_changes_since() returns all changes as a single byte array rather than individually split changes. This works for loadIncremental() / applyChanges() but callers expecting individual change objects should be aware.
  • decodeChange() returns partial data — the native implementation returns change metadata (hash, actor, timestamp, message, deps) but not the full ops array. This is sufficient for most use cases (e.g., MindooDB only uses hash and deps).
  • No WASM fallback — this is a complete replacement, not a supplement. The native backend is always used.

Development Notes

Post-Build Hook

The build process includes a post-build script (scripts/add-useapi-export.sh) that automatically injects the exports into index.ts after ubrn generates the bindings. This is necessary because ubrn regenerates index.ts from a template on each build.

The export line:

// IMPORTANT: Automerge export provides WASM-compatible API - do not remove!
export { nativeApi, NativeAutomerge, NativeSyncState, Automerge } from './useapi-adapter';

Critical: The Automerge export must always be present. If removed, applications using runtime detection (like MindooDB) will silently fall back to WASM mode, causing subtle bugs.

This export is automatically added after npm run build:ios or npm run build:android.

Automerge Version Alignment

  • Rust crate: automerge 0.7.3 (latest stable)
  • JS types: @automerge/automerge 3.2.1
  • Not using 1.0.0-beta — v1.0 has breaking changes (OpObserver removed, new patch API)
  • Stay on 0.7.x until 1.0.0 final release with migration guide

Testing

The package includes a comprehensive test suite with 40+ test cases covering all major Automerge operations.

# Install dependencies
npm install

# Build the native module first (required)
npm run build:ios  # or build:android

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm test -- --coverage

Test coverage includes:

  • Document creation, cloning, and manipulation
  • Map, List, Text, and Counter operations
  • Save/load persistence
  • Merge operations and conflict resolution
  • Change history and decodeChange()
  • Sync protocol
  • Complex nested structures
  • Proxy system behavior
  • Type conversions (ObjId, ChangeHash, ActorId, Cursor)

See tests/README.md for detailed test documentation.

Troubleshooting

Build fails with "conflicting types" error

UniFFI 0.29 requires bytes (not sequence<u8>) for custom types backed by Vec<u8> in the UDL file.

Android build fails with "unknown ABI"

Use NDK ABI names in ubrn.config.yaml: arm64-v8a, not aarch64-linux-android.

Tests fail with "Not implemented" error

You may be running on JSC instead of Hermes. This package requires Hermes (default in React Native 0.70+).

License

Apache 2.0

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0