@feedbackrelay/react-native-replay 0.0.0-stage → 0.1.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/AGENTS.md ADDED
@@ -0,0 +1,39 @@
1
+ # React Native replay agent guide
2
+
3
+ Read [README.md](README.md) and the host instructions. This optional package extends @feedbackrelay/react-native without adding encoders to core.
4
+
5
+ ## Public integration
6
+
7
+ Install @feedbackrelay/react-native@0.1.0 and @feedbackrelay/react-native-replay@0.1.0 from npm. Contributors can build/install both archives as shown in README.md to test source changes. Native sources and resources are already included; do not add standalone Swift/Kotlin packages to the same host.
8
+
9
+ Use Node.js 26/npm for this checkout's build and packaging commands; Node is a development tool, not a device/browser requirement.
10
+
11
+ `createReplayRecorder({fps?:'auto'|number})` returns a RelayReplayProvider. Default/invalid FPS is automatic, starting 1 and adapting 1–5; valid integer 1–10 is fixed. Duration is always 10 seconds. Pass `replay: recorder` at core client creation; reuse only across the same normalized backend/team/app. Different relays/keys may share that binding. The existing screenshot boolean ceilings both PNG/replay. A replay client never falls back to PNG.
12
+
13
+ The host owns UI/error handlers. No gestures, audio, polling endpoints or automatic app error interception. Context updates do not erase history. Identity changes require host cancellation, recorder.clear and context/retry replacement. Client.destroy detaches one owner; recorder.destroy is terminal.
14
+
15
+ History is up to ten seconds; startup/keyframes/budgets can shorten it. Apple guideline 2.5.14 requires host-owned explicit consent and recording indication. Do not enable attachment before those are in place; add no consent UI to this SDK.
16
+
17
+ ## Lifecycle and transport
18
+
19
+ Keep automatic-rate behavior and threshold changes aligned with the [automatic FPS rules](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#automatic-fps-rules). Do not claim identical iOS/Android/web policies or equate the selected target with measured throughput.
20
+
21
+ Opaque core hooks attach/freeze/accepted/cancel/detach must stay synchronous and cheap. Freeze pins existing compressed history before the event network request. Event-associated export/upload starts only after the durable receipt; an explicit local preview can mux/export before any send and never uploads. Never await media from core or change a successful event receipt because replay failed. The core onCollected observer carries JSON and an optional PNG (absent for replay); never put video bytes, URIs or status into it.
22
+
23
+ Keep one actual media worker, at most 4 leases, 60-second frozen lifetime and 30-second jobs. Ordinary main/sidechannel failure retains the original clip for explicit same-ID retry; never retry automatically or capture new history on an unknown retry. Capture-disabled retries discard prior image use without renewing lease lifetime. Cancellation aborts work but holds the worker/file until the actual read/export settles. No Promise.race that starts replacement work while an old file reader still owns resources.
24
+
25
+ Sidechannel: POST same relay URL + /replays, body {protocolVersion:1,submissionId,video:{mimeType:'video/mp4',byteSize,width,height,durationMs,startedBeforeEventMs,endedBeforeEventMs}} or omitted reason. Only pending+upload response permits binary multipart fields+file; storage has no key. Complete with POST /replays/{id}/complete body{}. Handle pending and terminal ready/omitted/failed/expired responses. No GET configuration or PNG fallback.
26
+
27
+ Read-only currentFPS:number|undefined reads existing native selected-rate state, not measured/encoded/delivered throughput. Inactive/backgrounded/unavailable/destroyed or failed native reads yield undefined. Do not add a sampling timer/upload or bridge calls after destroy.
28
+
29
+ ## Offline local preview
30
+
31
+ The concrete recorder exposes `preview(): Promise<ReplayPreview>`, with optional uri/omitted, byteSize/width/height/durationMs and idempotent release(). It never submits an event, invents a receipt or contacts the service. One pending/borrowed preview uses the existing worker, four lease slots, byte budgets and 60-second lifetime. Optional capture failures resolve omissions. Clear/destroy/runtime reload/expiry invalidate borrowed native URIs. Hosts copy before release with their existing file API; the SDK must not own player dependencies or delete the host copy. Preserve cleanup and stale-result handling when a preview is canceled/replaced. onCollected JSON remains binary-free; its separate optional PNG argument is absent for replay and never contains video.
32
+
33
+ ## Native and packaging
34
+
35
+ NativeRelayReplay spec/RelayReplaySpec bind thin Swift/ObjC++ and Kotlin adapters. Capture/mux are canonical native sources: stage iOS VideoRecorder.swift/resources and Android capture/encoder/buffer/plain provider only. Do not include native SDK HTTP delivery, duplicate encoders, base64 or JS file reads. Native capture returns a temporary MP4 URI and byte size. Keep it valid until JS networking finishes, release on completion/expiry/cancel and invalidate all leases on runtime reload.
36
+
37
+ Use RN >=0.86.3 <0.87, React ^19.2.3 and New Architecture; Expo Go/Legacy Architecture and native-package browser use are unsupported. Android minimum is API 24 with recording26+; iOS minimum is 15.1, with Xcode 16.1+ for RN 0.86.3 tooling. Hosts may raise OS minimums. Native bindings support only iOS/Android; React Native Windows/macOS are unsupported. Respect protected/background content and privacy generations. Local recorder failures are omissions; callbacks/cleanup must not throw through the app. Preserve required manifests/notices; no new dependencies or permissions.
38
+
39
+ Build/type/unit/Codegen/pack checks require both native consumer builds from archives without sibling sources. Run Android/iOS sequentially and verify binary MP4 content, ownership, retry and cancellation. Tests, scripts and native build dependencies are not packed. The SDK uses the [Apache License 2.0](LICENSE). Include the license and preserve third-party notices when distributing it. Do not publish without instruction.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # Relay replay for 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
+ Optional video history for `@feedbackrelay/react-native`. The addon records up to the previous ten seconds of your app window, freezes that history when you call `send`, and uploads an MP4 after the event is accepted. Startup, keyframe eviction and resource limits can make a clip shorter. It adds no UI, audio, gestures or automatic error handlers.
4
+
5
+ The core SDK works without this package. It does not include the recorder or video encoder.
6
+
7
+ ## 1. Install and rebuild
8
+
9
+ Use React Native `>=0.86.3 <0.87`, New Architecture and compatible React `^19.2.3`. Minimums are iOS 15.1 and Android API 24. Android recording needs API 26; older versions omit video while event delivery continues. RN 0.86.3 iOS tooling requires Xcode 16.1+. Hosts can require higher OS versions. Expo requires a native development/production build; Expo Go and Legacy Architecture are unsupported. Native bindings support only iOS/Android; React Native Windows/macOS are unsupported. Browser targets use the independent web SDK replay entry.
10
+
11
+ From your app folder, install the core SDK and optional replay addon:
12
+
13
+ ```sh
14
+ npm install @feedbackrelay/react-native@0.1.0 @feedbackrelay/react-native-replay@0.1.0
15
+ ```
16
+
17
+ Install pods/rebuild using your host's normal native workflow. Expo can use `npx expo run:ios` or `npx expo run:android`. JavaScript reload alone cannot install the module. The package includes its canonical recorder sources and privacy resources; do not install separate Swift/Kotlin replay packages in the same app.
18
+
19
+ ### Local archives for contributors
20
+
21
+ To test source changes before publishing another version, use Node.js 26/npm and a complete repository checkout to pack the core first, then this addon:
22
+
23
+ ```sh
24
+ cd "/path/to/relay-sdk/sdk/react-native"
25
+ npm ci
26
+ npm pack
27
+ cd "/path/to/relay-sdk/sdk/react-native-replay"
28
+ npm ci
29
+ npm pack
30
+ ```
31
+
32
+ Install both archives in your app:
33
+
34
+ ```sh
35
+ npm install "/path/to/feedbackrelay-react-native-0.1.0.tgz" "/path/to/feedbackrelay-react-native-replay-0.1.0.tgz"
36
+ ```
37
+
38
+ Reinstall the archives after source changes and rebuild when native code changes.
39
+
40
+ ## 2. Attach a recorder
41
+
42
+ For iOS, your host must obtain explicit consent and provide a recording indication as required by [Apple guideline 2.5.14](https://developer.apple.com/app-store/review/guidelines/#software-requirements). The SDK supplies neither consent UI nor an indicator. Attach an enabled replay client only after your app has handled those requirements.
43
+
44
+ ```ts
45
+ import { createRelayClient } from '@feedbackrelay/react-native';
46
+ import { createReplayRecorder } from '@feedbackrelay/react-native-replay';
47
+
48
+ const recorder = createReplayRecorder({ fps: 'auto' });
49
+ const relay = createRelayClient({
50
+ appId: 'com.example.app',
51
+ teamId: 'your-team-id',
52
+ relayId: 'your-relay-id',
53
+ publishableKey: 'your-publishable-key',
54
+ replay: recorder,
55
+ });
56
+
57
+ function sendMessage(message: string): void {
58
+ void relay.send({ message });
59
+ }
60
+ ```
61
+
62
+ Call `sendMessage(message)` from your existing Submit/error action; creating the owner should not send a report. Keep both objects in an app owner or React ref. A recorder starts only when attached to an enabled, foreground app client. Share it across clients only when their backend URL, team and app ID match. Each client still has its own relay ID and key. There are no settings GET requests.
63
+
64
+ Reuse one recorder object. Extra recorder instances omit capture while another owns it. Destroying the owner releases that guard after its active media job settles.
65
+
66
+ `fps` defaults to automatic: it starts at 1 and adapts within 1–5 based on available resources. An integer 1–10 selects a fixed rate. Invalid values fall back to automatic. History is always ten seconds; there is no duration option.
67
+
68
+ Read `const selectedFPS = recorder.currentFPS` for the selected adaptive/fixed target. It is undefined when recording is inactive, unavailable, backgrounded or destroyed. This is not measured encoded/delivered FPS. The getter reads existing native state; no SDK timer or uploaded telemetry is added. Refresh your own label only while needed.
69
+
70
+ **Automatic FPS:** The addon uses the underlying iOS/Android controller, not a separate JavaScript policy. Their cost/resource thresholds differ, and three healthy checks are needed per increase. Auto may remain at 1; a selected rate is not a throughput measurement. See the [exact native rules](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md#automatic-fps-rules).
71
+
72
+ With `replay` configured, the core never captures PNG, even when video is unavailable. Client/per-send `screenshot: false` prohibits video too. A globally disabled-only client does not start recording.
73
+
74
+ ## 3. Play a local preview before sending
75
+
76
+ Call `await recorder.preview()` from your own Preview action after a few seconds of foreground recording. It makes no event/upload request and needs no running Relay service. The result contains optional `uri`/`omitted`, `byteSize`, `width`, `height`, `durationMs` and `release()`.
77
+
78
+ The URI is borrowed. Copy it into your app's own cache with your host's file API **before** calling `release()`, then pass that copied URI to your existing player. Use `try/finally` to release on success or error. Do not play the borrowed URI after release: clear, destroy or its 60-second expiry can remove it. The SDK adds no file-copy or player library. Remove the host-owned copy when playback is replaced/closed; it uses storage outside SDK budgets.
79
+
80
+ Only one preview can be pending/held at a time, sharing existing lease, worker and byte limits. Missing history, prohibited/unsupported capture or busy resources return an omission. A later send independently freezes event history; a preview is not a receipt or accepted replay. `onCollected` has collected JSON plus an optional PNG argument; a replay client supplies no PNG, and video always uses this separate preview API.
81
+
82
+ ## 4. Understand completion and retry
83
+
84
+ `await relay.send(data)` waits for the event receipt, not video export/upload. Catch the normal event failure as described in the core guide. Ignored event promises are internally handled. Video work is best effort and never changes a successful receipt or shows SDK UI. The core send's optional `onCollected` callback never includes video; local video preview is separate from post-receipt upload.
85
+
86
+ A frozen lease lasts at most 60 seconds. Ordinary event/upload failure retains its original history/artifact for an explicit same-client, same-ID retry within that window. The addon never retries automatically. A retry without surviving history reports an omission; it does not record a different moment. Turning capture off on a retry prevents use of an earlier retained clip.
87
+
88
+ The addon runs one media job at a time, with a 30-second job budget and at most four leases. Cancellation holds file ownership until a running read/export settles. No media bytes or base64 are read into JavaScript; networking uploads a private native file URI.
89
+
90
+ ## 5. Stop or clear recording
91
+
92
+ ```ts
93
+ // On logout or another user identity boundary:
94
+ // Cancel old-user sends and remove saved retries first.
95
+ recorder.clear();
96
+ relay.clearContext();
97
+
98
+ // When permanently removing one client:
99
+ relay.destroy();
100
+ // When permanently removing the shared recorder:
101
+ recorder.destroy();
102
+ ```
103
+
104
+ Context changes do not clear video. `clear()` discards history and outstanding clips but leaves attached clients able to record new history. `destroy()` is terminal. Destroying one client detaches only that client's work; other clients sharing the recorder continue.
105
+
106
+ ## Capture and privacy
107
+
108
+ Only the app's own window is recorded. Backgrounding, unavailable/protected content, unsupported codecs and resource pressure can omit video. Android protected windows are respected. The addon does not request screen-sharing, microphone or storage permissions and records no audio.
109
+
110
+ Visible app content may contain personal information. Native video is not automatically redacted. Enable it only where your app intends to share that content. No history is persisted as an ongoing recording; private MP4 files exist only for active leases and are removed on completion, expiry or cleanup. System codecs use temporary memory in addition to retained compressed media; peak RAM and CPU overhead have not been benchmarked.
111
+
112
+ Clips use H.264 in MP4, even dimensions up to 720 pixels per edge and at most 2 MiB. The recorder bounds compressed history/lease reservations at 8 MiB. The iOS privacy manifest documents relative timing access; all capture/muxing uses platform frameworks, with no third-party video library.
113
+
114
+ ## Service requests
115
+
116
+ After the event receipt, the addon sends `POST /v1/sdk/teams/{teamId}/relays/{relayId}/replays` with `X-Relay-Key`, `protocolVersion:1`, the original `submissionId` and either video metadata or an omission reason. A pending response supplies a binary upload ticket. The addon uploads multipart `video/mp4` without the key on the storage request, then sends `{}` to `/replays/{id}/complete`.
117
+
118
+ The backend validates file length, dimensions and timing. Video failures stay separate from event acceptance. See the shared [service contract](https://github.com/apal21/relay-sdk/blob/main/sdk/CONTRACT.md).
119
+
120
+ After a receipt, cancelling the completed send does not stop its separate media job. Destroy that client to cancel its media, or clear the recorder to discard all retained history and media.
121
+
122
+ ## Development checks
123
+
124
+ ```sh
125
+ npm run build
126
+ npm test
127
+ npm run codegen
128
+ npm pack
129
+ ```
130
+
131
+ Run native consumer checks one platform at a time, installing both packed archives without sibling source folders. Verify actual MP4 upload, protected/background omission, retry expiry, cancellation, file cleanup and runtime reload. Codegen alone does not test a recorder on a device. Licensed under the [Apache License 2.0](LICENSE). Third-party components retain their own licenses. These commands do not publish the package.
@@ -0,0 +1,20 @@
1
+ require 'json'
2
+ package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
3
+ Pod::Spec.new do |s|
4
+ s.name = 'RelayReplay'
5
+ s.version = package['version']
6
+ s.summary = package['description']
7
+ s.homepage = 'https://github.com/apal21/relay-sdk'
8
+ s.license = { :type => 'Apache-2.0', :file => 'LICENSE' }
9
+ s.author = 'Relay SDK'
10
+ s.source = { :path => '.' }
11
+ s.platforms = { :ios => '15.1' }
12
+ s.module_name = 'RelayReplay'
13
+ s.swift_version = '5.9'
14
+ s.source_files = 'ios/**/*.{h,m,mm,swift}', 'native/ios/**/*.swift'
15
+ s.private_header_files = 'ios/RCTRelayReplay.h'
16
+ s.resource_bundles = { 'RelayReplayResources' => ['native/ios/Resources/**/*'] }
17
+ s.frameworks = 'UIKit', 'AVFoundation', 'VideoToolbox'
18
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'SWIFT_OBJC_INTERFACE_HEADER_NAME' => 'RelayReplay-Swift.h' }
19
+ install_modules_dependencies(s)
20
+ end
@@ -0,0 +1,17 @@
1
+ apply plugin: 'com.android.library'
2
+ apply plugin: 'org.jetbrains.kotlin.android'
3
+ apply plugin: 'com.facebook.react'
4
+ react { jsRootDir = file('../src'); libraryName = 'RelayReplaySpec'; codegenJavaPackageName = 'app.feedbackrelay.reactnativereplay' }
5
+ android {
6
+ namespace 'app.feedbackrelay.reactnativereplay'
7
+ compileSdk rootProject.ext.has('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
8
+ defaultConfig { minSdk 24 }
9
+ sourceSets.main { java.srcDirs += ['../native/android/java']; manifest.srcFile '../native/android/AndroidManifest.xml' }
10
+ compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
11
+ kotlinOptions { jvmTarget = '17' }
12
+ }
13
+ dependencies { implementation 'com.facebook.react:react-android' }
14
+
15
+ tasks.withType(Zip).matching { it.name.endsWith('Aar') }.configureEach {
16
+ from('../LICENSE')
17
+ }
@@ -0,0 +1,121 @@
1
+ package app.feedbackrelay.reactnativereplay
2
+
3
+ import android.app.Application
4
+ import android.os.Handler
5
+ import android.os.Looper
6
+ import android.net.Uri
7
+ import com.facebook.react.bridge.Promise
8
+ import com.facebook.react.bridge.ReactApplicationContext
9
+ import com.facebook.react.module.annotations.ReactModule
10
+ import app.feedbackrelay.sdk.RelayReplayAttachment
11
+ import app.feedbackrelay.sdk.RelayReplayDestination
12
+ import app.feedbackrelay.sdk.RelayReplayLease
13
+ import app.feedbackrelay.replay.RelayReplayCapture
14
+ import org.json.JSONObject
15
+ import java.util.UUID
16
+
17
+ @ReactModule(name = RelayReplayModule.NAME)
18
+ class RelayReplayModule(private val context: ReactApplicationContext) : NativeRelayReplaySpec(context) {
19
+ companion object { const val NAME = "RelayReplay" }
20
+ private data class Owner(val recorder: String, val value: RelayReplayAttachment)
21
+ private class Lease(val recorder: String, val owner: String, val value: RelayReplayLease) {
22
+ var promise: Promise? = null
23
+ var timeout: Runnable? = null
24
+ }
25
+ private val main = Handler(Looper.getMainLooper())
26
+ private val recorders = mutableMapOf<String, RelayReplayCapture>()
27
+ private val owners = mutableMapOf<String, Owner>()
28
+ private val leases = mutableMapOf<String, Lease>()
29
+ private var invalidated = false
30
+ @Synchronized override fun create(optionsJson: String): String = safely("") {
31
+ check(!invalidated)
32
+ val options = JSONObject(optionsJson)
33
+ val fps = (options.opt("fps") as? Number)?.toInt()?.takeIf { it in 1..10 }
34
+ val id = UUID.randomUUID().toString()
35
+ recorders[id] = RelayReplayCapture(context.applicationContext as Application, fps)
36
+ id
37
+ }
38
+ @Synchronized override fun getCurrentFPS(recorderId: String): Double = safely(0.0) {
39
+ if (invalidated) 0.0 else recorders[recorderId]?.currentFps?.toDouble() ?: 0.0
40
+ }
41
+ @Synchronized override fun attach(optionsJson: String): String = safely("") {
42
+ check(!invalidated)
43
+ val options = JSONObject(optionsJson); val recorderID = options.getString("recorderId")
44
+ val recorder = checkNotNull(recorders[recorderID])
45
+ val destination = RelayReplayDestination(options.getString("baseUrl"), options.getString("teamId"), options.getString("relayId"),
46
+ options.getString("publishableKey"), options.getString("appId"), captureEnabled = options.optBoolean("enabled", false))
47
+ val value = recorder.attach(destination)
48
+ context.currentActivity?.let(recorder::observe)
49
+ val id = UUID.randomUUID().toString(); owners[id] = Owner(recorderID, value); id
50
+ }
51
+ @Synchronized override fun freeze(optionsJson: String): String = safely("") {
52
+ check(!invalidated)
53
+ val options = JSONObject(optionsJson); val ownerID = options.getString("attachmentId"); val owner = checkNotNull(owners[ownerID])
54
+ val value = owner.value.freeze(options.getString("submissionId"), context.currentActivity,
55
+ options.optBoolean("allowed", false), options.optBoolean("isRetry", false))
56
+ val id = UUID.randomUUID().toString(); leases[id] = Lease(owner.recorder, ownerID, value); id
57
+ }
58
+ @Synchronized override fun preview(optionsJson: String): String = safely("") {
59
+ check(!invalidated)
60
+ val ownerID = JSONObject(optionsJson).getString("attachmentId"); val owner = checkNotNull(owners[ownerID])
61
+ val recorder = checkNotNull(recorders[owner.recorder])
62
+ context.currentActivity?.let(recorder::observe)
63
+ val value = recorder.freezePreview(owner.value)
64
+ val id = UUID.randomUUID().toString(); leases[id] = Lease(owner.recorder, ownerID, value); id
65
+ }
66
+ @Synchronized override fun materialize(leaseId: String, promise: Promise) {
67
+ val lease = leases[leaseId]
68
+ val recorder = lease?.let { recorders[it.recorder] }
69
+ if (invalidated || lease == null || recorder == null || lease.promise != null) {
70
+ quietly { promise.reject("E_REPLAY", "Replay lease is unavailable.") }; return
71
+ }
72
+ lease.promise = promise
73
+ val timeout = Runnable { release(leaseId) }; lease.timeout = timeout; main.postDelayed(timeout, 30_000)
74
+ try {
75
+ recorder.materialize(lease.value) { video ->
76
+ synchronized(this) {
77
+ if (leases[leaseId] !== lease || invalidated) return@synchronized
78
+ val callback = lease.promise ?: return@synchronized
79
+ lease.promise = null; lease.timeout?.let(main::removeCallbacks); lease.timeout = null
80
+ try {
81
+ val value = JSONObject().put("width", video.width).put("height", video.height).put("durationMs", video.durationMs)
82
+ .put("startedBeforeEventMs", video.startedBeforeEventMs).put("endedBeforeEventMs", video.endedBeforeEventMs)
83
+ if (video.omitted != null) value.put("omitted", video.omitted)
84
+ val file = video.file
85
+ if (file != null && file.isFile) value.put("uri", Uri.fromFile(file).toString()).put("byteSize", file.length())
86
+ quietly { callback.resolve(value.toString()) }
87
+ } catch (_: Exception) { quietly { callback.reject("E_REPLAY", "Could not materialize replay.") } }
88
+ }
89
+ }
90
+ } catch (_: Exception) {
91
+ lease.promise = null; main.removeCallbacks(timeout); lease.timeout = null
92
+ quietly { promise.reject("E_REPLAY", "Could not materialize replay.") }
93
+ }
94
+ }
95
+ @Synchronized override fun release(leaseId: String): Boolean {
96
+ val lease = leases.remove(leaseId) ?: return true
97
+ lease.timeout?.let(main::removeCallbacks); lease.timeout = null
98
+ val promise = lease.promise; lease.promise = null
99
+ quietly { owners[lease.owner]?.value?.cancel(lease.value) }
100
+ if (promise != null) quietly { promise.reject("E_CANCELLED", "Replay lease was released.") }
101
+ return true
102
+ }
103
+ @Synchronized override fun detach(attachmentId: String): Boolean {
104
+ val owner = owners[attachmentId] ?: return true
105
+ leases.filterValues { it.owner == attachmentId }.keys.toList().forEach(::release)
106
+ owners.remove(attachmentId); quietly { owner.value.detach() }; return true
107
+ }
108
+ @Synchronized override fun clear(recorderId: String): Boolean {
109
+ leases.filterValues { it.recorder == recorderId }.keys.toList().forEach(::release)
110
+ quietly { recorders[recorderId]?.clear() }; return true
111
+ }
112
+ @Synchronized override fun destroy(recorderId: String): Boolean {
113
+ owners.filterValues { it.recorder == recorderId }.keys.toList().forEach(::detach)
114
+ clear(recorderId); val recorder = recorders.remove(recorderId); quietly { recorder?.destroy() }; return true
115
+ }
116
+ @Synchronized override fun invalidate() {
117
+ invalidated = true; recorders.keys.toList().forEach(::destroy); quietly { super.invalidate() }
118
+ }
119
+ private inline fun <T> safely(fallback: T, action: () -> T): T = try { action() } catch (_: Exception) { fallback }
120
+ private inline fun quietly(action: () -> Unit) { try { action() } catch (_: Exception) {} }
121
+ }
@@ -0,0 +1,17 @@
1
+ package app.feedbackrelay.reactnativereplay
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+
9
+ class RelayReplayPackage : BaseReactPackage() {
10
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? =
11
+ if (name == RelayReplayModule.NAME) RelayReplayModule(reactContext) else null
12
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
13
+ mapOf(RelayReplayModule.NAME to ReactModuleInfo(
14
+ RelayReplayModule.NAME, RelayReplayModule::class.java.name, false, false, false, true,
15
+ ))
16
+ }
17
+ }
@@ -0,0 +1,4 @@
1
+ #import <RelayReplaySpec/RelayReplaySpec.h>
2
+ #import <React/RCTInvalidating.h>
3
+ @interface RCTRelayReplay : NativeRelayReplaySpecBase <NativeRelayReplaySpec, RCTInvalidating>
4
+ @end
@@ -0,0 +1,68 @@
1
+ #import "RCTRelayReplay.h"
2
+ #import "RelayReplay-Swift.h"
3
+ @implementation RCTRelayReplay { RelayReplayBridge *_bridge; }
4
+ RCT_EXPORT_MODULE(RelayReplay)
5
+ + (BOOL)requiresMainQueueSetup { return YES; }
6
+ - (instancetype)init { if ((self = [super init])) _bridge = [RelayReplayBridge new]; return self; }
7
+ - (NSString *)create:(NSString *)json {
8
+ __block NSString *value = @"";
9
+ void (^work)(void) = ^{ value = [self->_bridge create:json]; };
10
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
11
+ return value;
12
+ }
13
+ - (NSNumber *)getCurrentFPS:(NSString *)identifier {
14
+ __block double value = 0;
15
+ void (^work)(void) = ^{ value = [self->_bridge getCurrentFPS:identifier]; };
16
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
17
+ return @(value);
18
+ }
19
+ - (NSString *)attach:(NSString *)json {
20
+ __block NSString *value = @"";
21
+ void (^work)(void) = ^{ value = [self->_bridge attach:json]; };
22
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
23
+ return value;
24
+ }
25
+ - (NSString *)freeze:(NSString *)json {
26
+ __block NSString *value = @"";
27
+ void (^work)(void) = ^{ value = [self->_bridge freeze:json]; };
28
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
29
+ return value;
30
+ }
31
+ - (NSString *)preview:(NSString *)json {
32
+ __block NSString *value = @"";
33
+ void (^work)(void) = ^{ value = [self->_bridge preview:json]; };
34
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
35
+ return value;
36
+ }
37
+ - (NSNumber *)release:(NSString *)identifier {
38
+ __block BOOL value = NO;
39
+ void (^work)(void) = ^{ value = [self->_bridge release:identifier]; };
40
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
41
+ return @(value);
42
+ }
43
+ - (NSNumber *)detach:(NSString *)identifier {
44
+ __block BOOL value = NO;
45
+ void (^work)(void) = ^{ value = [self->_bridge detach:identifier]; };
46
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
47
+ return @(value);
48
+ }
49
+ - (NSNumber *)clear:(NSString *)identifier {
50
+ __block BOOL value = NO;
51
+ void (^work)(void) = ^{ value = [self->_bridge clear:identifier]; };
52
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
53
+ return @(value);
54
+ }
55
+ - (NSNumber *)destroy:(NSString *)identifier {
56
+ __block BOOL value = NO;
57
+ void (^work)(void) = ^{ value = [self->_bridge destroy:identifier]; };
58
+ if ([NSThread isMainThread]) work(); else dispatch_sync(dispatch_get_main_queue(), work);
59
+ return @(value);
60
+ }
61
+ - (void)materialize:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
62
+ dispatch_async(dispatch_get_main_queue(), ^{ [self->_bridge materialize:identifier resolve:resolve reject:reject]; });
63
+ }
64
+ - (void)invalidate { RelayReplayBridge *bridge = _bridge; dispatch_async(dispatch_get_main_queue(), ^{ [bridge invalidate]; }); }
65
+ - (std::shared_ptr<facebook::react::TurboModule>)getTurboModule:(const facebook::react::ObjCTurboModule::InitParams &)params {
66
+ return std::make_shared<facebook::react::NativeRelayReplaySpecJSI>(params);
67
+ }
68
+ @end