Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ Our pre-commit hooks verify that your commit message matches this format when co
Releases are published by the `release` job in `.github/workflows/ci.yml` when a version tag is pushed.
Only maintainers can do this.

1. In a pull request to `main`, bump `version` in `package.json` and `PACKAGE_VERSION` in `src/core/config.ts`.
A test fails if the two differ.
1. In a pull request to `main`, bump `version` in `package.json`.
2. After the pull request is merged, tag the merge commit on `main` with a tag named `vX.Y.Z`, where
`X.Y.Z` is the version:

Expand Down
10 changes: 6 additions & 4 deletions NOTICE
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
react-native-tinode
Copyright 2026 amerllica

This product is a TypeScript re-implementation of tinode-js (tinode-sdk),
https://github.com/tinode/tinode-js, Copyright Tinode LLC, licensed under the
Apache License, Version 2.0. The source was ported module by module and modified
to run on React Native (Hermes) as well as in web browsers.
This product depends on tinode-sdk (tinode-js), https://github.com/tinode/tinode-js,
Copyright Tinode LLC, licensed under the Apache License, Version 2.0.

The TypeScript declarations in src/sdk/types/ describe the tinode-sdk API and are
derived from its source. The grapheme splitter and UTF-8 decoder in src/platform are
original work of this project.
44 changes: 28 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
# react-native-tinode

[Tinode](https://github.com/tinode/chat) chat client for React Native and the web, written in TypeScript.

It is a port of the official JavaScript SDK ([tinode-js](https://github.com/tinode/tinode-js) v0.25.4) that does not
depend on browser APIs, plus a set of React hooks.
React hooks and providers for [Tinode](https://github.com/tinode/chat) chat on React Native and the web, on top of
the official JavaScript SDK, [tinode-sdk](https://github.com/tinode/tinode-js).

- iOS, Android and web. Works in Expo Go and in bare React Native.
- No native code and no runtime dependencies.
- Typed protocol messages, topics, Drafty documents and contact cards.
- No native code.
- TypeScript types for the whole SDK: protocol messages, topics, Drafty documents and contact cards.
- Offline cache: IndexedDB on the web; `expo-sqlite`, MMKV or AsyncStorage on native, in one line.

## Installation
Expand All @@ -16,6 +14,11 @@ depend on browser APIs, plus a set of React hooks.
yarn add react-native-tinode
```

`tinode-sdk` comes with it. Until the next `tinode-sdk` release is on npm, it is installed from a pinned commit of
the [tinode-js](https://github.com/tinode/tinode-js) `devel` branch, so installing needs `git` and `npm` on the
machine and access to github.com (all three are on CI runners and EAS build images). Networks that block git or
GitHub cannot install it until then.

## Quick start

```tsx
Expand Down Expand Up @@ -60,7 +63,7 @@ On the Android emulator the example rewrites `localhost` to `10.0.2.2`.

## Using the client directly

The core API follows tinode-js, so its [documentation](https://tinode.github.io/js-api/) applies.
`Tinode` is the `tinode-sdk` client, so its [documentation](https://tinode.github.io/js-api/) applies.

```ts
import { createTinode } from 'react-native-tinode';
Expand Down Expand Up @@ -100,15 +103,18 @@ added through `attach(target, 'onData', fn)`, which you can use too.

## Reconnecting

The provider reconnects when the app comes back to the foreground. To also reconnect when the network comes back,
pass NetInfo:
The provider reconnects when the app comes back to the foreground. When the connection drops, the client retries with
a growing delay. To retry at once when the network comes back, pass NetInfo in the config:

```tsx
import NetInfo from '@react-native-community/netinfo';

<TinodeProvider config={config} netInfo={NetInfo}>
<TinodeProvider config={{ ...config, netInfo: NetInfo }}>
```

`netInfo` is anything with `addEventListener(listener)` that returns an unsubscribe function and calls the listener
with `{ isConnected }`, so a small wrapper over the browser `online` and `offline` events works on the web too.

## Persistence

By default nothing is cached (`persist: false`). With a cache, your app can show chats at once on start, and chats
Expand Down Expand Up @@ -137,7 +143,8 @@ The store is your app's dependency, not this library's. To keep users signed in
`tinode.getLargeFileHelper()` uploads and downloads attachments.

- `upload()` accepts a web `Blob`/`File` or a React Native file object `{ uri, name, type }`.
- `download()` saves the file in the browser. On native it resolves with the `Blob`, and saving it is up to you.
- `download()` saves the file in the browser. It does not work on native yet: the current `tinode-sdk` needs a DOM
for it. Until the fix is released upstream, download attachments yourself with `fetch` and the auth token.

## Push notifications

Expand All @@ -151,11 +158,16 @@ registerDeviceToken(tinode, await messaging().getToken());
With Expo, use `(await Notifications.getDevicePushTokenAsync()).data`. The server sends FCM data messages; how to
show them is up to the app.

## Differences from tinode-js
## What this package adds to tinode-sdk

- Providers and hooks with shared topic subscriptions, paging and typing state.
- TypeScript types. `tinode-sdk` is plain JavaScript and ships no types.
- Two small polyfills for Hermes, installed only when missing: `Intl.Segmenter` (grapheme level only, used by Drafty)
and a UTF-8 `TextDecoder` (used by vCard import). Import `react-native-tinode` before `tinode-sdk` so they are in
place when the SDK loads.
- `isCommError(error)`, because `tinode-sdk` does not export its `CommError` class.

- No global polyfills. Nothing touches `window`, `document` or `navigator` without checking first.
- `Tinode.setDatabaseProvider()` is gone. Use the `storage` option.
- A number of upstream bugs are fixed. See [docs/DECISIONS.md](docs/DECISIONS.md) for the reasoning behind the port.
See [docs/DECISIONS.md](docs/DECISIONS.md) for the reasoning.

## Contributing

Expand All @@ -165,4 +177,4 @@ show them is up to the app.

## License

Apache-2.0. Based on [tinode-js](https://github.com/tinode/tinode-js) by Tinode LLC, see [NOTICE](NOTICE).
Apache-2.0. Uses [tinode-sdk](https://github.com/tinode/tinode-js) by Tinode LLC, see [NOTICE](NOTICE).
136 changes: 70 additions & 66 deletions docs/DECISIONS.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,77 @@
# Decisions

## 1. Re-implement tinode-js in TypeScript instead of wrapping `tinode-sdk`

The first plan was to wrap the `tinode-sdk` npm package and add types and shims around it.
We chose a full TypeScript port instead.

Reasons:

- `tinode-sdk` assumes a browser at many points: `window.location` in `LargeFileHelper`,
`document` for downloads, `indexedDB` for the cache, `Intl.Segmenter` in Drafty,
`navigator.userAgent` in the constructor, and an import-time shim that writes `global.window`.
Shimming these from outside the bundle is fragile and changes global state for the whole app.
- The SDK has no types. Hand-written `.d.ts` files drift from the runtime.
- Storage is hard-wired to IndexedDB. A port lets us put storage behind an adapter now,
without an upstream change.

Cost: protocol fixes in upstream do not arrive automatically. Track upstream releases and port
relevant changes by hand. The port targets tinode-js **v0.25.4**; `VERSION` in
`src/core/config.ts` is the version sent to the server and must match the ported feature level.

## 2. Module layout mirrors upstream

`src/core/*.ts` keeps upstream file names, class names, method names and argument order.
This keeps the port easy to diff against upstream releases and keeps the public API familiar to
existing Tinode users.

## 3. Storage is an adapter

`StorageAdapter` (`src/core/storage/storage-adapter.ts`) is a small record-based interface with
no SDK classes in it. `PersistentCache` does all Topic ↔ record mapping and keeps the upstream
`DB` method names.

- Web: `IndexedDBAdapter` uses the same database name, version and schema as upstream, so an
existing browser cache stays valid.
- Native: `KeyValueAdapter` wraps any key-value store the app already has (`expo-sqlite/kv-store`,
MMKV through `fromMMKV`, AsyncStorage). The library imports none of them, so it keeps zero
dependencies and still runs in Expo Go. The store's shape is a TypeScript interface, and a test
checks it against each store's published typings.
- `KeyValueAdapter` extends `MemoryAdapter`: it loads the whole cache on open and writes every
change through. That is fine for contacts and recent chats. A SQLite adapter for large offline
histories is planned for 0.2.0 (issue #1).
- No eviction: the cache keeps every message it has seen, like the upstream web client.
- `MemoryAdapter` exists for tests and for a session-only cache.

`Tinode.setDatabaseProvider()` from upstream is removed. Use the `storage` config key.

## 4. Platform rules

- No browser globals without a `typeof` guard. No writes to globals.
- `Intl.Segmenter` is missing on Hermes: Drafty uses a fallback grapheme splitter.
- `TextDecoder` may be missing: TheCard has a UTF-8 fallback.
- `new Blob([ArrayBuffer])` and object URLs for such Blobs throw on React Native: code falls
back to `data:` URIs.
- `LargeFileHelper.download()` saves the file through the DOM on web (upstream behaviour). Where
there is no DOM it resolves with the downloaded `Blob`; saving it is the app's job.
- `LargeFileHelper.upload()` accepts a React Native file descriptor `{ uri, name, type }` as
well as a web `Blob`/`File`.
## 1. Wrap `tinode-sdk` instead of porting it

Until 0.1.x this package carried its own TypeScript port of tinode-js, because `tinode-sdk` assumed a browser and had
IndexedDB hard-wired. [tinode/tinode-js#103](https://github.com/tinode/tinode-js/pull/103) moved the platform
dependencies into the SDK's config: `storage` (any storage adapter), `netInfo` (reconnect when the network is back)
and `network` (`WebSocket` and `XMLHttpRequest`). With that merged, the port has no reason to exist: protocol fixes
now arrive with `tinode-sdk` instead of being ported by hand.

This package keeps only what the SDK does not do: React providers and hooks, TypeScript types, and two Hermes
polyfills (section 4).

## 2. `tinode-sdk` is pinned to a GitHub commit until the next release

The merged work is on the tinode-js `devel` branch and not on npm yet, so `package.json` depends on
`github:tinode/tinode-js#commit=<sha>`. Yarn downloads that commit, runs `npm install` and `npm pack` in it once, and
stores the packed checksum in `yarn.lock`, so CI installs are reproducible. When a release with the change is on npm,
replace the pin with a version range.

The pin also reaches every app that installs this package: their install fetches tinode-js from GitHub and needs
`git` and `npm`. Each release note says so until the pin is gone.

## 3. Types live in `src/sdk`

`tinode-sdk` is plain JavaScript and ships no types.

- `src/sdk/types/` declares the SDK surface, one file per area (Drafty, TheCard, storage, topics, wire messages, the
client): classes as `declare class` (so each name is both the instance type and the constructor), plus the
protocol and storage types. `src/sdk/types/index.ts` lists the public names one by one, so internal helper types
stay out of the package API. It started as the declarations of the old port, which had
the same API, and is aligned with upstream where they differ (`network` option, `setDatabaseProvider`, the socket
shape upstream uses).
- `src/sdk/tinode-sdk.d.ts` tells TypeScript what the untyped module exports, using only inline imports from
`./types`, so emitted declarations never refer to `tinode-sdk` itself.
- `src/sdk/index.ts` re-exports the values with those types. Constants that upstream only has as `Tinode` statics
(`MESSAGE_STATUS_*`, `DEL_CHAR`) are exported as plain constants.

Upstream does not export `Topic`, `TopicMe`, `TopicFnd`, `CommError`, `MetaGetBuilder` or `LargeFileHelper`, so they
are types only. Instances come from the client (`getTopic`, `getMeTopic`, `startMetaQuery`, `getLargeFileHelper`).
`isCommError` replaces `instanceof CommError`. `TOPIC_ME`, `LOCAL_SEQID` and `DEFAULT_MESSAGES_PAGE` are not exported
upstream either; the React layer keeps its own copies in `src/react/constants.ts`.

When `tinode-sdk` changes its API, update `src/sdk/types/` by hand. `src/sdk/__tests__/sdk.test.ts` loads the real
SDK, so a missing export fails there. The goal is to move these declarations into tinode-js, so that `tinode-sdk`
ships its own types and `src/sdk` shrinks to the re-exports.

## 4. Hermes polyfills

`tinode-sdk` calls `new Intl.Segmenter()` when it loads (Drafty) and uses `TextDecoder` for vCard import. Hermes
has neither. `src/platform` installs a grapheme-only `Intl.Segmenter` and a UTF-8-only `TextDecoder`, each only when
the global is missing, and `src/index.tsx` imports it before the SDK. `package.json` lists `src/platform` and
`lib/module/platform` in `sideEffects`, so web bundlers keep the import.

These go away when tinode-js ships its own fallbacks (planned as the next upstream PR, together with downloads without
a DOM). Until then `LargeFileHelper.download()` works on the web only.

## 5. React layer

Hooks live in `src/react`. Tinode callbacks are single-slot properties, so the hooks attach
listeners through a small multiplexer instead of overwriting app callbacks.
NetInfo is not a dependency, not even an optional one. A guarded `require` of an optional package
breaks bare React Native builds, because Metro defaults `allowOptionalDependencies` to `false`.
Apps that want reconnect on network change pass their NetInfo module to the provider
(`netInfo={NetInfo}`). Without it, reconnect still happens on `AppState` change and through the
SDK's own backoff.
Hooks live in `src/react`. Tinode callbacks are single-slot properties, so the hooks attach listeners through a small
multiplexer instead of overwriting app callbacks.

NetInfo is not a dependency, not even an optional one. A guarded `require` of an optional package breaks bare React
Native builds, because Metro defaults `allowOptionalDependencies` to `false`. Apps that want a fast reconnect pass
their NetInfo module in the config (`netInfo: NetInfo`); the SDK then retries at once when the network comes back.
The provider still reconnects on `AppState` change: `AppState` is React Native only, and the SDK has no app
lifecycle hook, so the foreground reconnect belongs to the React layer.

## 6. Storage

Storage adapters come from `tinode-sdk`: `IndexedDBAdapter` (the default in browsers when `persist` is on),
`KeyValueAdapter` over any key-value store the app already has (`expo-sqlite/kv-store`, MMKV through `fromMMKV`,
AsyncStorage) and `MemoryAdapter`. This package imports none of the stores, so it still runs in Expo Go.

## 6. License
## 7. License

The port is a derivative work of tinode-js (Apache-2.0). This package is released under
Apache-2.0, with attribution in `NOTICE`.
This package is released under Apache-2.0. It depends on tinode-sdk (Apache-2.0), with attribution in `NOTICE`.
2 changes: 1 addition & 1 deletion docs/persistence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ The cache is never the source of truth. The server is. Deleting the cache loses
| Bare React Native, or an Expo development build that wants the fastest store | `react-native-mmkv` | [mmkv.md](mmkv.md) |
| Already uses AsyncStorage | `@react-native-async-storage/async-storage` | [async-storage.md](async-storage.md) |
| Web | nothing to do: `persist: true` uses IndexedDB | below |
| Thousands of messages per chat kept offline | SQLite adapter, planned for 0.2.0 | [issue #1](https://github.com/amerllica/react-native-tinode/issues/1) |
| Thousands of messages per chat kept offline | SQLite adapter, planned | [issue #1](https://github.com/amerllica/react-native-tinode/issues/1) |

The login token does not belong in this cache. See [auth-token.md](auth-token.md).

Expand Down
4 changes: 2 additions & 2 deletions docs/persistence/auth-token.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ Use a secure store for the token, not the chat cache:
```tsx
import * as SecureStore from 'expo-secure-store';
import { useEffect } from 'react';
import { CommError, useLogin } from 'react-native-tinode';
import { isCommError, useLogin } from 'react-native-tinode';

const TOKEN_KEY = 'tinode-token';
const UNAUTHORIZED = 401;

function isRejectedToken(error: unknown) {
return error instanceof CommError && error.code === UNAUTHORIZED;
return isCommError(error) && error.code === UNAUTHORIZED;
}

export function useRememberedLogin() {
Expand Down
12 changes: 0 additions & 12 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,6 @@ export default defineConfig([
'prettier/prettier': 'error',
},
},
{
files: ['src/core/**/*.ts'],
rules: {
'no-bitwise': 'off',
},
},
{
files: ['src/core/__tests__/drafty.test.ts'],
rules: {
'no-script-url': 'off',
},
},
{
ignores: ['node_modules/', 'lib/'],
},
Expand Down
14 changes: 10 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "react-native-tinode",
"version": "0.1.1",
"description": "Tinode chat SDK for React Native and web, rewritten in TypeScript, with React hooks",
"description": "React and React Native hooks for Tinode chat, on top of the official tinode-sdk",
"main": "./lib/module/index.js",
"types": "./lib/typescript/src/index.d.ts",
"exports": {
Expand Down Expand Up @@ -53,6 +53,9 @@
"publishConfig": {
"registry": "https://registry.npmjs.org/"
},
"dependencies": {
"tinode-sdk": "github:tinode/tinode-js#commit=70436161b61efb1087de69f612692019f13fb2de"
},
"devDependencies": {
"@commitlint/config-conventional": "^21.2.0",
"@eslint/compat": "^2.1.0",
Expand All @@ -70,7 +73,6 @@
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-ft-flow": "^3.0.11",
"eslint-plugin-prettier": "^5.5.6",
"fake-indexeddb": "^6.2.5",
"jest": "^29.7.0",
"lefthook": "^2.1.10",
"prettier": "^3.9.6",
Expand Down Expand Up @@ -105,7 +107,8 @@
"project": "tsconfig.build.json"
}
]
]
],
"exclude": "{**/{__tests__,__fixtures__,__mocks__}/**,**/*.d.ts}"
},
"jest": {
"preset": "@react-native/jest-preset",
Expand Down Expand Up @@ -143,5 +146,8 @@
],
"version": "0.63.1"
},
"sideEffects": false
"sideEffects": [
"./src/platform/**",
"./lib/module/platform/**"
]
}
Loading
Loading