@zapiack/react-native 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # Changelog
2
+
3
+ All notable changes to @zapiack/react-native are listed here. Versions follow [semantic versioning](https://semver.org).
4
+
5
+ ## 0.2.0
6
+
7
+ - Realtime: `ZapiackRealtime` for live messages over one WebSocket (pure JavaScript): channels, presence, signals, resume after a dropped connection.
8
+ - Calls: `ZapiackCall` from `@zapiack/react-native/calls`, voice and video for one-to-one and group calls over the same connection, with camera switching, speaker routing and recovery when the phone changes network. Needs `react-native-webrtc` and `mediasoup-client`.
9
+
10
+ ## 0.1.0
11
+
12
+ First release.
13
+
14
+ Push for React Native on iOS and Android, as a thin bridge over the native libraries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zapiack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,172 @@
1
- # Temporary Holding Version
1
+ # @zapiack/react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The one Zapiack package for React Native apps. Push notifications are in it today, and new Zapiack products arrive in the same package.
4
+
5
+ ## Push
6
+
7
+ Registers the device, shows pushes with pictures and buttons, reports taps, and
8
+ follows what the person does next, so you can see which pushes bring people back.
9
+
10
+ Android 5.0+ and iOS 13+, React Native 0.71+. It has native code, so it does not run in Expo Go: use a development build.
11
+
12
+ ```bash
13
+ npm install @zapiack/react-native
14
+ cd ios && pod install
15
+ ```
16
+
17
+ ## Use it
18
+
19
+ ```ts
20
+ import { ZapiackPush } from '@zapiack/react-native';
21
+
22
+ await ZapiackPush.configure({
23
+ appKey: 'pk_…',
24
+ appGroup: 'group.com.example.app', // iOS only: see below
25
+ });
26
+
27
+ // Ask when it makes sense for your users, for example after a tap on a button.
28
+ const allowed = await ZapiackPush.requestPermission();
29
+
30
+ const stop = ZapiackPush.onTap((tap) => {
31
+ // tap.link, tap.actionId (the button), tap.event
32
+ });
33
+ const opened = await ZapiackPush.initialTap(); // the push that started the app, if any
34
+ ```
35
+
36
+ Link a device to your user and group devices with tags:
37
+
38
+ ```ts
39
+ await ZapiackPush.login('user_123');
40
+ await ZapiackPush.logout();
41
+ await ZapiackPush.addTags({ plan: 'pro' });
42
+ ```
43
+
44
+ Follow what happens after a tap. Both are credited to the push only for a short window after it was tapped:
45
+
46
+ ```ts
47
+ await ZapiackPush.screen('OrderDetails');
48
+ await ZapiackPush.track('purchase', { total: 49 });
49
+ ```
50
+
51
+ ## Android
52
+
53
+ Firebase Cloud Messaging has to be set up as in any Android app (`google-services.json` and the Google services plugin). The
54
+ package adds its own Firebase service. If another library also registers one, such as `@react-native-firebase/messaging`, only one
55
+ of them receives a push: call `ZapiackMessagingService.handle` from yours, as described in the Android library's README.
56
+
57
+ ## iOS
58
+
59
+ 1. In Xcode, turn on **Push Notifications** and **Background Modes → Remote notifications** for the app target.
60
+ 2. Add an **App Group** to the app target, and use its name as `appGroup`.
61
+ 3. Add a **Notification Service Extension** target with the same App Group, and make its class a subclass of
62
+ `ZapiackNotificationService` from the Zapiack iOS package (`ZapiackNotificationExtension`). The extension reports that a push
63
+ arrived and shows its picture and buttons. Without it, pushes still show, with no arrival report, picture or buttons.
64
+ 4. React Native does not pass the push address on, so forward it from `AppDelegate`:
65
+
66
+ ```objc
67
+ #import <zapiack_react_native/zapiack_react_native-Swift.h>
68
+
69
+ - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
70
+ [ZapiackPushModule didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
71
+ }
72
+ ```
73
+
74
+ ## Realtime
75
+
76
+ Live messages over one WebSocket: chat, live updates, presence, and signalling for calls. It is separate from push; use either or both.
77
+
78
+ Your app never holds an API key. Your **server** asks Zapiack for a short-lived token for the signed-in user (the key needs the **Realtime** scope, or no scope limits), and hands it to the app:
79
+
80
+ ```bash
81
+ curl -X POST https://api.zapiack.com/v1/realtime/tokens \
82
+ -H "Authorization: Bearer $ZAPIACK_API_KEY" -H "Content-Type: application/json" \
83
+ -d '{"userId":"user_42","capabilities":{"chat:*":["subscribe","publish","presence"]}}'
84
+ # → { "token": "eyJ…", "expiresAt": "…", "url": "wss://rt.zapiack.com/?token=eyJ…" }
85
+ ```
86
+
87
+ `capabilities` says what that user may do on which channels (`*` matches anything): `subscribe`, `publish`, `presence`, `history`, `signal`. Tokens last an hour unless you ask for less (`ttlSeconds`, at most a day).
88
+
89
+ In your app (plain JavaScript, no native setup):
90
+
91
+ ```ts
92
+ import { ZapiackRealtime } from '@zapiack/react-native';
93
+
94
+ const rt = new ZapiackRealtime({
95
+ // Ask YOUR server for a token. Called on every connect, so an expired token is replaced.
96
+ getToken: () => fetch('https://your.server/realtime-token').then((r) => r.text()),
97
+ });
98
+ await rt.connect();
99
+
100
+ const stop = rt.subscribe('chat:room-1', (m) => console.log(m.from, m.data));
101
+ await rt.publish('chat:room-1', { text: 'hi' }, { persist: true }); // resolves when the server confirms
102
+
103
+ const here = rt.presence('chat:room-1');
104
+ here.enter({ name: 'Ann' });
105
+ here.onChange(({ action, member }) => console.log(action, member.user));
106
+ rt.signal('call-7', otherConnectionId, 'offer', { sdp }); // to one connection
107
+ rt.onError((e) => console.warn(e.code, e.message));
108
+ ```
109
+
110
+ - **Reconnects by itself** with a growing, jittered pause, fetches a fresh token each time, re-joins every channel and replays what it missed since the last message it saw (publish with `persist` to make a message replayable). Messages already seen are not repeated.
111
+ - **Sends made while offline** wait (up to 100) and go out in order once the line is back.
112
+ - A message that cannot be replayed because the client was away longer than the project's retention is reported as an error with code 410: reload that channel's history over REST.
113
+ - The project can refuse a client for good (Realtime switched off, or the connection was removed in the dashboard). Then `connect` fails with code 403 and it does not retry.
114
+
115
+ ## Voice and video calls
116
+
117
+ Calls are a separate entry, so apps that only use push or messaging never load WebRTC.
118
+
119
+ ```
120
+ npm install react-native-webrtc mediasoup-client react-native-incall-manager
121
+ ```
122
+
123
+ Follow `react-native-webrtc`'s setup for your React Native version (camera and microphone permissions in `Info.plist` and `AndroidManifest.xml`, and the iOS pod install). Then:
124
+
125
+ ```tsx
126
+ import { ZapiackCall } from '@zapiack/react-native/calls';
127
+ import InCallManager from 'react-native-incall-manager';
128
+ import { RTCView } from 'react-native-webrtc';
129
+
130
+ const call = new ZapiackCall({
131
+ // Your server asks Zapiack for a token with POST /v1/calls/tokens (or starts the call with POST /v1/calls) and returns it here.
132
+ getToken: () => fetch('https://my-server.example/call-token').then((r) => r.text()),
133
+ // Earpiece, speaker and the phone's call mode.
134
+ audioSession: {
135
+ start: ({ media }) => InCallManager.start({ media }),
136
+ stop: () => InCallManager.stop(),
137
+ setSpeaker: (on) => InCallManager.setForceSpeakerphoneOn(on),
138
+ },
139
+ });
140
+
141
+ call.on('track', ({ identity, source, stream }) => setStreams((s) => ({ ...s, [`${identity}:${source}`]: stream.toURL() })));
142
+ call.on('trackEnded', ({ identity, source }) => setStreams(({ [`${identity}:${source}`]: _gone, ...rest }) => rest));
143
+ call.on('ended', ({ reason }) => navigation.goBack());
144
+
145
+ await call.join();
146
+ await call.enableMicrophone();
147
+ await call.enableCamera(); // front camera; pass { camera: 'environment' } in the options for the back one
148
+ call.setSpeaker(true);
149
+ call.switchCamera(); // front <-> back, without interrupting the video
150
+ await call.setMuted('audio', true);
151
+ await call.leave();
152
+
153
+ // <RTCView streamURL={streams['ada:video']} style={{ flex: 1 }} objectFit="cover" />
154
+ ```
155
+
156
+ A person who is a `listener` in the token can receive but never send. Audio from other people plays by itself; only video needs an `RTCView`.
157
+
158
+ A call also re-asks the server who is in the room every 30 seconds (`resyncMs` in the options, 0 turns it off), so an event that was missed costs seconds, not the rest of the call.
159
+
160
+ On a phone the network changes under a call (Wi-Fi to mobile data, a lift, a tunnel). The client waits a few seconds for the connection to recover, then restarts it with fresh parameters from the server, and if the socket itself dropped it rejoins the room and picks up who is there now.
161
+
162
+ **Not covered yet:** keeping a call alive in the background (iOS needs the `voip` background mode and CallKit; Android needs a foreground service) and screen sharing (`shareScreen` works once the Android foreground service and the iOS broadcast extension from `react-native-webrtc`'s guide are in place). Ringing a phone that is closed is done with push: see `POST /v1/calls`.
163
+
164
+ ## Maintaining
165
+
166
+ The iOS code in this package is copied from the iOS library: run `npm run sync-ios` after changing it (it also runs before publishing).
167
+
168
+ ## Tests
169
+
170
+ ```
171
+ npm test
172
+ ```
@@ -0,0 +1,48 @@
1
+ def safeExtGet(prop, fallback) {
2
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
3
+ }
4
+
5
+ buildscript {
6
+ repositories {
7
+ google()
8
+ mavenCentral()
9
+ }
10
+ dependencies {
11
+ classpath "com.android.tools.build:gradle:8.9.1"
12
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.20"
13
+ }
14
+ }
15
+
16
+ apply plugin: "com.android.library"
17
+ apply plugin: "kotlin-android"
18
+
19
+ android {
20
+ namespace "com.zapiack.reactnative"
21
+ compileSdk safeExtGet("compileSdkVersion", 35)
22
+
23
+ defaultConfig {
24
+ minSdk safeExtGet("minSdkVersion", 24)
25
+ }
26
+
27
+ compileOptions {
28
+ sourceCompatibility JavaVersion.VERSION_17
29
+ targetCompatibility JavaVersion.VERSION_17
30
+ }
31
+
32
+ kotlinOptions {
33
+ jvmTarget = "17"
34
+ }
35
+ }
36
+
37
+ repositories {
38
+ google()
39
+ mavenCentral()
40
+ // Only until the Android library is on Maven Central.
41
+ mavenLocal()
42
+ }
43
+
44
+ dependencies {
45
+ // The version comes from the app's React Native Gradle plugin.
46
+ implementation "com.facebook.react:react-android"
47
+ api "com.zapiack:zapiack-android:0.2.0"
48
+ }
@@ -0,0 +1 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,113 @@
1
+ package com.zapiack.reactnative
2
+
3
+ import android.Manifest
4
+ import android.content.Intent
5
+ import android.content.pm.PackageManager
6
+ import android.os.Build
7
+ import com.facebook.react.bridge.ActivityEventListener
8
+ import com.facebook.react.bridge.Arguments
9
+ import com.facebook.react.bridge.Promise
10
+ import com.facebook.react.bridge.ReactApplicationContext
11
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
12
+ import com.facebook.react.bridge.ReactMethod
13
+ import com.facebook.react.bridge.ReadableMap
14
+ import com.facebook.react.bridge.ReadableArray
15
+ import com.facebook.react.bridge.WritableMap
16
+ import com.facebook.react.modules.core.DeviceEventManagerModule
17
+ import com.facebook.react.modules.core.PermissionAwareActivity
18
+ import com.facebook.react.modules.core.PermissionListener
19
+ import com.zapiack.push.ZapiackPush
20
+ import com.zapiack.push.core.Tap
21
+
22
+ /** Connects the JavaScript API to the Android library. */
23
+ class ZapiackPushModule(private val reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext), ActivityEventListener {
24
+ init {
25
+ reactContext.addActivityEventListener(this)
26
+ }
27
+
28
+ override fun getName() = "ZapiackPush"
29
+
30
+ @ReactMethod
31
+ fun configure(options: ReadableMap, promise: Promise) {
32
+ val key = options.getString("appKey")
33
+ if (key == null || !key.startsWith("pk_")) return promise.reject("invalid_key", "The app key must start with pk_")
34
+ val base = if (options.hasKey("baseUrl")) options.getString("baseUrl") else null
35
+ if (base != null) ZapiackPush.configure(reactContext.applicationContext, key, base) else ZapiackPush.configure(reactContext.applicationContext, key)
36
+ promise.resolve(null)
37
+ }
38
+
39
+ @ReactMethod
40
+ fun requestPermission(promise: Promise) {
41
+ val context = reactContext.applicationContext
42
+ if (ZapiackPush.hasPermission(context)) {
43
+ promise.resolve(true)
44
+ return
45
+ }
46
+ val activity = reactContext.currentActivity
47
+ if (Build.VERSION.SDK_INT < 33 || activity !is PermissionAwareActivity) {
48
+ // Before Android 13 there is nothing to ask; without a React activity there is nobody to ask on.
49
+ promise.resolve(false)
50
+ return
51
+ }
52
+ // The answer has to come back through React's own activity, which is why the library's `requestPermission` is not used here.
53
+ activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_CODE, PermissionListener { code, _, results ->
54
+ if (code != REQUEST_CODE) return@PermissionListener false
55
+ ZapiackPush.onPermissionResult(code)
56
+ promise.resolve(results.isNotEmpty() && results[0] == PackageManager.PERMISSION_GRANTED)
57
+ true
58
+ })
59
+ }
60
+
61
+ @ReactMethod fun installationId(promise: Promise) = promise.resolve(ZapiackPush.installationId)
62
+
63
+ @ReactMethod fun login(userId: String, promise: Promise) { ZapiackPush.login(userId); promise.resolve(null) }
64
+
65
+ @ReactMethod fun logout(promise: Promise) { ZapiackPush.logout(); promise.resolve(null) }
66
+
67
+ @ReactMethod fun addTags(tags: ReadableMap, promise: Promise) { ZapiackPush.addTags(tags.toHashMap()); promise.resolve(null) }
68
+
69
+ @ReactMethod fun removeTags(keys: ReadableArray, promise: Promise) { ZapiackPush.removeTags(keys.toArrayList().map { it.toString() }); promise.resolve(null) }
70
+
71
+ @ReactMethod fun screen(name: String, promise: Promise) { ZapiackPush.screen(name); promise.resolve(null) }
72
+
73
+ @ReactMethod
74
+ fun track(name: String, properties: ReadableMap?, promise: Promise) {
75
+ promise.resolve(ZapiackPush.track(name, properties?.toHashMap()))
76
+ }
77
+
78
+ @ReactMethod fun flush(promise: Promise) { ZapiackPush.flush(); promise.resolve(null) }
79
+
80
+ /** Live Activities are iOS only; on Android a template's live parts are drawn in the notification with nothing to turn on. */
81
+ @ReactMethod fun enableLiveActivities(promise: Promise) { promise.resolve(null) }
82
+
83
+ /** The tap that opened the app. The library takes a tap out of the intent when it handles it, so a second call finds nothing. */
84
+ @ReactMethod
85
+ fun initialTap(promise: Promise) {
86
+ promise.resolve(ZapiackPush.handleIntent(reactContext.currentActivity?.intent)?.toMap())
87
+ }
88
+
89
+ // Required by NativeEventEmitter.
90
+ @ReactMethod fun addListener(eventName: String) = Unit
91
+ @ReactMethod fun removeListeners(count: Int) = Unit
92
+
93
+ override fun onNewIntent(intent: Intent) {
94
+ val tap = ZapiackPush.handleIntent(intent) ?: return
95
+ reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java).emit(TAP_EVENT, tap.toMap())
96
+ }
97
+
98
+ override fun onActivityResult(activity: android.app.Activity, requestCode: Int, resultCode: Int, data: Intent?) = Unit
99
+
100
+ private fun Tap.toMap(): WritableMap = Arguments.createMap().apply {
101
+ putString("messageId", messageId)
102
+ putString("deliveryId", deliveryId)
103
+ putString("sessionId", sessionId)
104
+ putString("actionId", actionId)
105
+ putString("event", event)
106
+ putString("link", link)
107
+ }
108
+
109
+ companion object {
110
+ private const val REQUEST_CODE = 7391
111
+ private const val TAP_EVENT = "zapiackTap"
112
+ }
113
+ }
@@ -0,0 +1,12 @@
1
+ package com.zapiack.reactnative
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ class ZapiackPushPackage : ReactPackage {
9
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> = listOf(ZapiackPushModule(reactContext))
10
+
11
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
12
+ }
@@ -0,0 +1,198 @@
1
+ import { Device } from 'mediasoup-client';
2
+ import { MediaStream, MediaStreamTrack } from 'react-native-webrtc';
3
+ import { ZapiackRealtime, RealtimeEnv, ZapiackRealtimeError } from './index.mjs';
4
+
5
+ /**
6
+ * Zapiack Voice & Video for React Native: join a room and send and receive audio and video.
7
+ *
8
+ * Your server creates the room and mints a token for each person (`POST /v1/calls/rooms`, `POST /v1/calls/tokens`) and hands it to
9
+ * the app, so the API key never reaches the phone. The app joins with the token:
10
+ *
11
+ * const call = new ZapiackCall({ getToken: () => fetch('https://my-server/call-token').then((r) => r.text()) });
12
+ * call.on('track', ({ identity, source, stream }) => show(identity, source, stream.toURL())); // <RTCView streamURL=... />
13
+ * await call.join();
14
+ * await call.enableMicrophone();
15
+ * await call.enableCamera();
16
+ *
17
+ * What a person may send comes from their token: a listener can only receive. Needs `react-native-webrtc` and `mediasoup-client`
18
+ * (both peer dependencies of this entry only; push and messaging do not need them).
19
+ */
20
+
21
+ /** Where sound plays. Wire it to `react-native-incall-manager` (see the README) so the earpiece, speaker and the phone's call mode work. */
22
+ interface AudioSession {
23
+ start(options: {
24
+ media: 'audio' | 'video';
25
+ }): void;
26
+ stop(): void;
27
+ setSpeaker(on: boolean): void;
28
+ }
29
+ type CallRole = 'host' | 'speaker' | 'listener';
30
+ /** What a track is: a microphone, a camera, or a shared screen. */
31
+ type TrackSource = 'audio' | 'video' | 'screen';
32
+ interface CallOptions {
33
+ /** Returns a call token from your server (`POST /v1/calls/tokens`). Called on every connect, so an expired one is replaced. */
34
+ getToken: () => Promise<string>;
35
+ /** Default `wss://rt.zapiack.com`. */
36
+ url?: string;
37
+ /** Send and receive over TCP only. For networks that block UDP. Default false. */
38
+ forceTcp?: boolean;
39
+ /** How often, in milliseconds, the client asks the server who is in the room and catches up on anything it missed. Default 30000. 0 turns it off. */
40
+ resyncMs?: number;
41
+ /** Sound routing and the phone's call mode. Started when the call is joined and stopped when it ends. */
42
+ audioSession?: AudioSession;
43
+ /** Which camera `enableCamera` opens first. Default `user` (the front one). */
44
+ camera?: 'user' | 'environment';
45
+ }
46
+ interface Peer {
47
+ identity: string;
48
+ role: CallRole;
49
+ }
50
+ /** Someone else's audio, video or screen. Give `stream.toURL()` to an `<RTCView streamURL={...} />`; audio plays by itself. */
51
+ interface RemoteTrack {
52
+ identity: string;
53
+ source: TrackSource;
54
+ track: MediaStreamTrack;
55
+ stream: MediaStream;
56
+ /** The sender's track id: the same one `trackEnded` and `paused` carry. */
57
+ producerId: string;
58
+ }
59
+ interface CallEvents {
60
+ /** Someone's track arrived. */
61
+ track: RemoteTrack;
62
+ /** Someone stopped sending a track, or left. */
63
+ trackEnded: {
64
+ identity: string;
65
+ source: TrackSource;
66
+ producerId: string;
67
+ };
68
+ /** Someone muted or unmuted a track. The track stays; what it carries is silence or a frozen picture. */
69
+ paused: {
70
+ identity: string;
71
+ source: TrackSource;
72
+ producerId: string;
73
+ paused: boolean;
74
+ };
75
+ peerJoined: Peer;
76
+ peerLeft: {
77
+ identity: string;
78
+ };
79
+ /** The room was ended by your server. The call is already closed when this fires. */
80
+ ended: {
81
+ reason: string;
82
+ };
83
+ /** A problem worth showing: a track that could not be played, or a refused request. */
84
+ error: ZapiackRealtimeError;
85
+ }
86
+ type CallState = 'idle' | 'joining' | 'joined' | 'reconnecting' | 'closed';
87
+ type Listener<K extends keyof CallEvents> = (e: CallEvents[K]) => void;
88
+ /** What can be swapped in a test. */
89
+ interface CallEnv {
90
+ realtime?: ZapiackRealtime;
91
+ realtimeEnv?: RealtimeEnv;
92
+ device?: () => Device;
93
+ getUserMedia?: (c: Record<string, unknown>) => Promise<MediaStream>;
94
+ getDisplayMedia?: () => Promise<MediaStream>;
95
+ newStream?: (tracks: MediaStreamTrack[]) => MediaStream;
96
+ setTimeout?: (fn: () => void, ms: number) => unknown;
97
+ clearTimeout?: (id: unknown) => void;
98
+ }
99
+ declare class ZapiackCall {
100
+ private readonly options;
101
+ private readonly env;
102
+ private readonly rt;
103
+ private readonly device;
104
+ private readonly listeners;
105
+ private sendT;
106
+ private recvT;
107
+ private readonly producers;
108
+ /** Everything being received, by the sender's track id. */
109
+ private readonly consumers;
110
+ private readonly peers;
111
+ private joinedReply;
112
+ private roomChannel;
113
+ private stopRoom;
114
+ private stopState;
115
+ private _state;
116
+ /** Tracks being fetched right now, so two events for the same track do not make two consumers. */
117
+ private readonly fetching;
118
+ private wasConnected;
119
+ private resyncing;
120
+ private resyncTimer;
121
+ private facing;
122
+ private speaker;
123
+ /** A transport that went `disconnected` gets a few seconds to recover by itself before its path is restarted. */
124
+ private readonly lapse;
125
+ constructor(options: CallOptions, env?: CallEnv);
126
+ get state(): CallState;
127
+ /** What this person may do in the room: `listener` can only receive. */
128
+ get role(): CallRole | null;
129
+ get roomId(): string | null;
130
+ /** Who else is in the room now. */
131
+ get members(): Peer[];
132
+ /** The tracks this person is sending now. */
133
+ get sending(): TrackSource[];
134
+ on<K extends keyof CallEvents>(event: K, fn: Listener<K>): () => void;
135
+ private emit;
136
+ /** Connects, joins the room the token is for, and starts receiving what the others are sending. */
137
+ join(): Promise<{
138
+ role: CallRole;
139
+ roomId: string;
140
+ members: Peer[];
141
+ }>;
142
+ /** Turns the microphone on and sends it. Pass your own track to send something else. */
143
+ enableMicrophone(track?: MediaStreamTrack): Promise<MediaStreamTrack>;
144
+ /** Turns the camera on and sends it. Opens the camera set by the `camera` option, front by default. */
145
+ enableCamera(track?: MediaStreamTrack): Promise<MediaStreamTrack>;
146
+ /**
147
+ * Shares the phone's screen. Android needs a foreground service for screen capture and iOS needs a broadcast extension: see
148
+ * react-native-webrtc's screen sharing guide. Stops by itself when the person stops sharing.
149
+ */
150
+ shareScreen(track?: MediaStreamTrack): Promise<MediaStreamTrack>;
151
+ /** Mutes or unmutes what is being sent. Nothing is sent while muted, and the others are told. */
152
+ setMuted(source: TrackSource, muted: boolean): Promise<void>;
153
+ /** Flips between the front and back camera while the camera is on, without interrupting what is being sent. */
154
+ switchCamera(): void;
155
+ /** Plays sound through the loudspeaker (true) or the earpiece (false). Needs an `audioSession` option; remembered across a reconnect. */
156
+ setSpeaker(on: boolean): void;
157
+ isMuted(source: TrackSource): boolean;
158
+ /** Stops sending a track and lets go of the device (the camera light goes off). */
159
+ stop(source: TrackSource): Promise<void>;
160
+ /**
161
+ * What is arriving now, one entry per track being received: how many bytes and packets, how many were lost, and the jitter in
162
+ * seconds. For a quality indicator, or to see that media is really flowing.
163
+ */
164
+ stats(): Promise<Array<{
165
+ identity: string;
166
+ source: TrackSource;
167
+ bytesReceived: number;
168
+ packetsReceived: number;
169
+ packetsLost: number;
170
+ jitter: number;
171
+ }>>;
172
+ /** Leaves the room and lets go of the camera, the microphone and the connection. */
173
+ leave(): Promise<void>;
174
+ private userMedia;
175
+ private displayMedia;
176
+ private transport;
177
+ private restartIce;
178
+ private send;
179
+ private reconcile;
180
+ private consume;
181
+ private endTrack;
182
+ private dropFrom;
183
+ private onRoomEvent;
184
+ /** Who this person is in the room, as the server knows them: events about this name are about us. */
185
+ private identity;
186
+ /**
187
+ * Room events travel over best-effort publish and subscribe, so a client does not rely on every one arriving: now and then it asks the
188
+ * server who is in the room and what they are sending, and catches up on anything it missed.
189
+ */
190
+ private startResync;
191
+ private resync;
192
+ /** The socket dropped and came back: take the place in the room again and see what changed while away. */
193
+ private onLine;
194
+ private teardown;
195
+ }
196
+
197
+ export { ZapiackCall };
198
+ export type { AudioSession, CallEnv, CallEvents, CallOptions, CallRole, CallState, Peer, RemoteTrack, TrackSource };