livevoice-sdk-react-native 2.0.0 → 3.0.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.
Files changed (221) hide show
  1. package/README.md +158 -7
  2. package/android/build.gradle +18 -6
  3. package/android/src/main/java/io/livevoice/react/LiveVoiceModule.kt +121 -221
  4. package/android/src/main/java/io/livevoice/react/__SDK.kt +17 -3
  5. package/ios/LiveVoiceRNBridge.swift +362 -0
  6. package/ios/LiveVoiceSdkReactNative.mm +247 -145
  7. package/ios/__SDK.h +16 -2
  8. package/ios/livevoice_spm_backport.rb +202 -0
  9. package/lib/module/components/BrandingView.js +71 -50
  10. package/lib/module/components/BrandingView.js.map +1 -1
  11. package/lib/module/components/ChannelView.js +368 -54
  12. package/lib/module/components/ChannelView.js.map +1 -1
  13. package/lib/module/components/ErrorView.js +17 -16
  14. package/lib/module/components/ErrorView.js.map +1 -1
  15. package/lib/module/components/LiveVoiceSpinner.js +81 -0
  16. package/lib/module/components/LiveVoiceSpinner.js.map +1 -0
  17. package/lib/module/components/LiveVoiceView.js +351 -104
  18. package/lib/module/components/LiveVoiceView.js.map +1 -1
  19. package/lib/module/components/PasswordPrompt.js +165 -0
  20. package/lib/module/components/PasswordPrompt.js.map +1 -0
  21. package/lib/module/components/PlayButtonView.js +192 -254
  22. package/lib/module/components/PlayButtonView.js.map +1 -1
  23. package/lib/module/components/ReconnectingView.js +43 -62
  24. package/lib/module/components/ReconnectingView.js.map +1 -1
  25. package/lib/module/components/WarningView.js +12 -10
  26. package/lib/module/components/WarningView.js.map +1 -1
  27. package/lib/module/icons/branding-ios.png +0 -0
  28. package/lib/module/icons/camera-off-android.png +0 -0
  29. package/lib/module/icons/camera-off-android@2x.png +0 -0
  30. package/lib/module/icons/camera-off-android@3x.png +0 -0
  31. package/lib/module/icons/cpu-android.png +0 -0
  32. package/lib/module/icons/cpu-android@2x.png +0 -0
  33. package/lib/module/icons/cpu-android@3x.png +0 -0
  34. package/lib/module/icons/cpu-ios.png +0 -0
  35. package/lib/module/icons/cpu-ios@2x.png +0 -0
  36. package/lib/module/icons/cpu-ios@3x.png +0 -0
  37. package/lib/module/icons/lock-android.png +0 -0
  38. package/lib/module/icons/lock-android@2x.png +0 -0
  39. package/lib/module/icons/lock-android@3x.png +0 -0
  40. package/lib/module/icons/lock-ios.png +0 -0
  41. package/lib/module/icons/lock-ios@2x.png +0 -0
  42. package/lib/module/icons/lock-ios@3x.png +0 -0
  43. package/lib/module/icons/mic-off-android.png +0 -0
  44. package/lib/module/icons/mic-off-android@2x.png +0 -0
  45. package/lib/module/icons/mic-off-android@3x.png +0 -0
  46. package/lib/module/icons/mic-slash-ios.png +0 -0
  47. package/lib/module/icons/mic-slash-ios@2x.png +0 -0
  48. package/lib/module/icons/mic-slash-ios@3x.png +0 -0
  49. package/lib/module/icons/video-slash-ios.png +0 -0
  50. package/lib/module/icons/video-slash-ios@2x.png +0 -0
  51. package/lib/module/icons/video-slash-ios@3x.png +0 -0
  52. package/lib/module/index.js +24 -225
  53. package/lib/module/index.js.map +1 -1
  54. package/lib/module/sdk/Bridge.js +236 -0
  55. package/lib/module/sdk/Bridge.js.map +1 -0
  56. package/lib/module/sdk/Event.js +160 -0
  57. package/lib/module/sdk/Event.js.map +1 -0
  58. package/lib/module/sdk/Lifecycle.js +331 -0
  59. package/lib/module/sdk/Lifecycle.js.map +1 -0
  60. package/lib/module/sdk/LiveVoiceSdk.js +365 -0
  61. package/lib/module/sdk/LiveVoiceSdk.js.map +1 -0
  62. package/lib/module/sdk/LiveVoiceState.js +234 -0
  63. package/lib/module/sdk/LiveVoiceState.js.map +1 -0
  64. package/lib/module/sdk/LogEntries.js +99 -0
  65. package/lib/module/sdk/LogEntries.js.map +1 -0
  66. package/lib/module/sdk/Models.js +2 -0
  67. package/lib/module/{util/UIState.js.map → sdk/Models.js.map} +1 -1
  68. package/lib/module/sdk/NativeSdkVersions.js +24 -0
  69. package/lib/module/sdk/NativeSdkVersions.js.map +1 -0
  70. package/lib/module/sdk/Observables.js +391 -0
  71. package/lib/module/sdk/Observables.js.map +1 -0
  72. package/lib/module/sdk/Passwords.js +298 -0
  73. package/lib/module/sdk/Passwords.js.map +1 -0
  74. package/lib/module/sdk/Playback.js +35 -0
  75. package/lib/module/sdk/Playback.js.map +1 -0
  76. package/lib/module/specs/NativeLiveVoiceSdk.js +12 -10
  77. package/lib/module/specs/NativeLiveVoiceSdk.js.map +1 -1
  78. package/lib/module/util/Colors.js +14 -11
  79. package/lib/module/util/Colors.js.map +1 -1
  80. package/lib/module/util/Translations.js +46 -21
  81. package/lib/module/util/Translations.js.map +1 -1
  82. package/lib/module/util/freeze.js +26 -0
  83. package/lib/module/util/freeze.js.map +1 -0
  84. package/lib/module/util/logger.js +114 -0
  85. package/lib/module/util/logger.js.map +1 -0
  86. package/lib/typescript/src/components/BrandingView.d.ts +4 -0
  87. package/lib/typescript/src/components/BrandingView.d.ts.map +1 -1
  88. package/lib/typescript/src/components/ChannelView.d.ts +29 -3
  89. package/lib/typescript/src/components/ChannelView.d.ts.map +1 -1
  90. package/lib/typescript/src/components/ErrorView.d.ts +5 -3
  91. package/lib/typescript/src/components/ErrorView.d.ts.map +1 -1
  92. package/lib/typescript/src/components/LiveVoiceSpinner.d.ts +16 -0
  93. package/lib/typescript/src/components/LiveVoiceSpinner.d.ts.map +1 -0
  94. package/lib/typescript/src/components/LiveVoiceView.d.ts +85 -3
  95. package/lib/typescript/src/components/LiveVoiceView.d.ts.map +1 -1
  96. package/lib/typescript/src/components/PasswordPrompt.d.ts +13 -0
  97. package/lib/typescript/src/components/PasswordPrompt.d.ts.map +1 -0
  98. package/lib/typescript/src/components/PlayButtonView.d.ts +12 -329
  99. package/lib/typescript/src/components/PlayButtonView.d.ts.map +1 -1
  100. package/lib/typescript/src/components/ReconnectingView.d.ts +6 -3
  101. package/lib/typescript/src/components/ReconnectingView.d.ts.map +1 -1
  102. package/lib/typescript/src/components/WarningView.d.ts.map +1 -1
  103. package/lib/typescript/src/index.d.ts +15 -144
  104. package/lib/typescript/src/index.d.ts.map +1 -1
  105. package/lib/typescript/src/sdk/Bridge.d.ts +36 -0
  106. package/lib/typescript/src/sdk/Bridge.d.ts.map +1 -0
  107. package/lib/typescript/src/sdk/Event.d.ts +97 -0
  108. package/lib/typescript/src/sdk/Event.d.ts.map +1 -0
  109. package/lib/typescript/src/sdk/Lifecycle.d.ts +191 -0
  110. package/lib/typescript/src/sdk/Lifecycle.d.ts.map +1 -0
  111. package/lib/typescript/src/sdk/LiveVoiceSdk.d.ts +215 -0
  112. package/lib/typescript/src/sdk/LiveVoiceSdk.d.ts.map +1 -0
  113. package/lib/typescript/src/sdk/LiveVoiceState.d.ts +80 -0
  114. package/lib/typescript/src/sdk/LiveVoiceState.d.ts.map +1 -0
  115. package/lib/typescript/src/sdk/LogEntries.d.ts +28 -0
  116. package/lib/typescript/src/sdk/LogEntries.d.ts.map +1 -0
  117. package/lib/typescript/src/sdk/Models.d.ts +114 -0
  118. package/lib/typescript/src/sdk/Models.d.ts.map +1 -0
  119. package/lib/typescript/src/sdk/NativeSdkVersions.d.ts +6 -0
  120. package/lib/typescript/src/sdk/NativeSdkVersions.d.ts.map +1 -0
  121. package/lib/typescript/src/sdk/Observables.d.ts +123 -0
  122. package/lib/typescript/src/sdk/Observables.d.ts.map +1 -0
  123. package/lib/typescript/src/sdk/Passwords.d.ts +72 -0
  124. package/lib/typescript/src/sdk/Passwords.d.ts.map +1 -0
  125. package/lib/typescript/src/sdk/Playback.d.ts +9 -0
  126. package/lib/typescript/src/sdk/Playback.d.ts.map +1 -0
  127. package/lib/typescript/src/specs/NativeLiveVoiceSdk.d.ts +35 -29
  128. package/lib/typescript/src/specs/NativeLiveVoiceSdk.d.ts.map +1 -1
  129. package/lib/typescript/src/util/Colors.d.ts.map +1 -1
  130. package/lib/typescript/src/util/Translations.d.ts +30 -8
  131. package/lib/typescript/src/util/Translations.d.ts.map +1 -1
  132. package/lib/typescript/src/util/freeze.d.ts +6 -0
  133. package/lib/typescript/src/util/freeze.d.ts.map +1 -0
  134. package/lib/typescript/src/util/logger.d.ts +33 -0
  135. package/lib/typescript/src/util/logger.d.ts.map +1 -0
  136. package/livevoice-sdk-react-native.podspec +41 -16
  137. package/package.json +26 -14
  138. package/src/components/BrandingView.tsx +55 -66
  139. package/src/components/ChannelView.tsx +342 -48
  140. package/src/components/ErrorView.tsx +21 -22
  141. package/src/components/LiveVoiceSpinner.tsx +87 -0
  142. package/src/components/LiveVoiceView.tsx +360 -151
  143. package/src/components/PasswordPrompt.tsx +144 -0
  144. package/src/components/PlayButtonView.tsx +177 -279
  145. package/src/components/ReconnectingView.tsx +40 -86
  146. package/src/components/WarningView.tsx +12 -10
  147. package/src/icons/branding-ios.png +0 -0
  148. package/src/icons/camera-off-android.png +0 -0
  149. package/src/icons/camera-off-android@2x.png +0 -0
  150. package/src/icons/camera-off-android@3x.png +0 -0
  151. package/src/icons/cpu-android.png +0 -0
  152. package/src/icons/cpu-android@2x.png +0 -0
  153. package/src/icons/cpu-android@3x.png +0 -0
  154. package/src/icons/cpu-ios.png +0 -0
  155. package/src/icons/cpu-ios@2x.png +0 -0
  156. package/src/icons/cpu-ios@3x.png +0 -0
  157. package/src/icons/lock-android.png +0 -0
  158. package/src/icons/lock-android@2x.png +0 -0
  159. package/src/icons/lock-android@3x.png +0 -0
  160. package/src/icons/lock-ios.png +0 -0
  161. package/src/icons/lock-ios@2x.png +0 -0
  162. package/src/icons/lock-ios@3x.png +0 -0
  163. package/src/icons/mic-off-android.png +0 -0
  164. package/src/icons/mic-off-android@2x.png +0 -0
  165. package/src/icons/mic-off-android@3x.png +0 -0
  166. package/src/icons/mic-slash-ios.png +0 -0
  167. package/src/icons/mic-slash-ios@2x.png +0 -0
  168. package/src/icons/mic-slash-ios@3x.png +0 -0
  169. package/src/icons/video-slash-ios.png +0 -0
  170. package/src/icons/video-slash-ios@2x.png +0 -0
  171. package/src/icons/video-slash-ios@3x.png +0 -0
  172. package/src/index.tsx +105 -252
  173. package/src/sdk/Bridge.ts +259 -0
  174. package/src/sdk/Event.ts +187 -0
  175. package/src/sdk/Lifecycle.ts +366 -0
  176. package/src/sdk/LiveVoiceSdk.ts +384 -0
  177. package/src/sdk/LiveVoiceState.ts +259 -0
  178. package/src/sdk/LogEntries.ts +88 -0
  179. package/src/sdk/Models.ts +129 -0
  180. package/src/sdk/NativeSdkVersions.ts +21 -0
  181. package/src/sdk/Observables.ts +414 -0
  182. package/src/sdk/Passwords.ts +286 -0
  183. package/src/sdk/Playback.ts +30 -0
  184. package/src/specs/NativeLiveVoiceSdk.ts +56 -46
  185. package/src/util/Colors.ts +14 -11
  186. package/src/util/Translations.ts +46 -22
  187. package/src/util/freeze.ts +23 -0
  188. package/src/util/logger.ts +119 -0
  189. package/android/app/build/generated/source/codegen/java/com/facebook/fbreact/specs/NativeLiveVoiceSdkSpec.java +0 -186
  190. package/android/app/build/generated/source/codegen/jni/CMakeLists.txt +0 -28
  191. package/android/app/build/generated/source/codegen/jni/RNLiveVoiceSpec-generated.cpp +0 -235
  192. package/android/app/build/generated/source/codegen/jni/RNLiveVoiceSpec.h +0 -31
  193. package/android/app/build/generated/source/codegen/jni/react/renderer/components/RNLiveVoiceSpec/RNLiveVoiceSpecJSI.h +0 -341
  194. package/android/src/main/java/io/livevoice/react/Mappings.kt +0 -85
  195. package/android/src/main/java/io/livevoice/react/NativeModels.kt +0 -79
  196. package/lib/module/components/AudioOutputSwitchView.js +0 -138
  197. package/lib/module/components/AudioOutputSwitchView.js.map +0 -1
  198. package/lib/module/components/index.js +0 -22
  199. package/lib/module/components/index.js.map +0 -1
  200. package/lib/module/icons/mic.png +0 -0
  201. package/lib/module/util/ForegroundServiceConfig.js +0 -28
  202. package/lib/module/util/ForegroundServiceConfig.js.map +0 -1
  203. package/lib/module/util/PlayingState.js +0 -21
  204. package/lib/module/util/PlayingState.js.map +0 -1
  205. package/lib/module/util/UIState.js +0 -4
  206. package/lib/typescript/src/components/AudioOutputSwitchView.d.ts +0 -6
  207. package/lib/typescript/src/components/AudioOutputSwitchView.d.ts.map +0 -1
  208. package/lib/typescript/src/components/index.d.ts +0 -9
  209. package/lib/typescript/src/components/index.d.ts.map +0 -1
  210. package/lib/typescript/src/util/ForegroundServiceConfig.d.ts +0 -12
  211. package/lib/typescript/src/util/ForegroundServiceConfig.d.ts.map +0 -1
  212. package/lib/typescript/src/util/PlayingState.d.ts +0 -7
  213. package/lib/typescript/src/util/PlayingState.d.ts.map +0 -1
  214. package/lib/typescript/src/util/UIState.d.ts +0 -66
  215. package/lib/typescript/src/util/UIState.d.ts.map +0 -1
  216. package/src/components/AudioOutputSwitchView.tsx +0 -146
  217. package/src/components/index.tsx +0 -19
  218. package/src/icons/mic.png +0 -0
  219. package/src/util/ForegroundServiceConfig.tsx +0 -32
  220. package/src/util/PlayingState.ts +0 -18
  221. package/src/util/UIState.ts +0 -89
@@ -0,0 +1,259 @@
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // This source file is part of the LiveVoice SDK project
4
+ //
5
+ // Copyright (c) LiveVoice GmbH
6
+ // Licensed under the MIT license
7
+ //
8
+ // See LICENSE for license information
9
+ //
10
+ // SPDX-License-Identifier: MIT
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ // Internal: the wrapper's side of the native wrapper bridge (bridge.md). It hydrates a cache of
15
+ // every state from the snapshot `initialize` returns, keeps it current from the one `onState`
16
+ // callback, and drops any delivery whose revision is not newer than the one it holds. Nothing here
17
+ // is exported from the package entry point.
18
+
19
+ import Native from '../specs/NativeLiveVoiceSdk';
20
+ import { logDecodeError, logListenerError } from '../util/logger';
21
+ import {
22
+ bridgeDidInitialize,
23
+ receivePasswordRequest,
24
+ receivePasswordRequestCancellation,
25
+ receivePasswordStoreRequest,
26
+ } from './Passwords';
27
+
28
+ /** The states on the wire (bridge.md 2.1). */
29
+ export type StateName =
30
+ | 'connection'
31
+ | 'defaultView'
32
+ | 'features'
33
+ | 'audioOutput'
34
+ | 'subtitles'
35
+ | 'availableSubtitles'
36
+ | 'currentEvent'
37
+ | 'requestableLanguages'
38
+ | 'linkedEvents';
39
+
40
+ const stateNames: readonly StateName[] = [
41
+ 'connection',
42
+ 'defaultView',
43
+ 'features',
44
+ 'audioOutput',
45
+ 'subtitles',
46
+ 'availableSubtitles',
47
+ 'currentEvent',
48
+ 'requestableLanguages',
49
+ 'linkedEvents',
50
+ ];
51
+
52
+ /** A delivered value; `decoded` is whether the state's decoder, if it has one, could read it. */
53
+ type Envelope = { revision: number; value: unknown; encoded: string; decoded: boolean };
54
+
55
+ const states = new Map<StateName, Envelope>();
56
+ /** The latest revision of each state whose value was decoded and applied (bridge.md 1.3). */
57
+ const appliedRevisions = new Map<StateName, number>();
58
+ /** The one decoder of each state that has one: a public store, or the default view's model. */
59
+ const decoders = new Map<StateName, (value: unknown) => boolean>();
60
+ const observers = new Map<StateName, Set<(value: unknown) => void>>();
61
+ let initialized = false;
62
+ let subscribed = false;
63
+ let errorMessages: Record<string, string> | undefined;
64
+
65
+ /** Created once per JavaScript runtime; a different one tells native that the runtime is new. */
66
+ export const runtimeId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
67
+
68
+ /** Whether `initialize` has hydrated the cache. */
69
+ export function isInitialized(): boolean {
70
+ return initialized;
71
+ }
72
+
73
+ /** The latest value of `name` as JSON, which changes exactly when the value does. */
74
+ export function currentEncoded(name: StateName): string | undefined {
75
+ return states.get(name)?.encoded;
76
+ }
77
+
78
+ type RevisionWaiter = { targets: [StateName, number][]; done: () => void };
79
+ const revisionWaiters = new Set<RevisionWaiter>();
80
+
81
+ /** How long a command's reply waits for its states before resolving anyway (18 item 133). */
82
+ export const revisionWaitMillis = 5_000;
83
+
84
+ /**
85
+ * Resolves once every state named in a reply's `revisions` (bridge.md 3.3) has applied that
86
+ * revision or a newer one, so `getCurrent…()` shows the command's result right after `await`. Only
87
+ * a value its decoder read counts; a state without a decoder counts on arrival. A state that never
88
+ * applies, for example after an undecodable delivery, stops the wait after five seconds: the
89
+ * command succeeded, so it never fails because of it.
90
+ */
91
+ export function awaitRevisions(revisions: unknown): Promise<void> {
92
+ if (!record(revisions)) return Promise.resolve();
93
+ const targets = Object.entries(revisions).filter(
94
+ (entry): entry is [StateName, number] =>
95
+ stateNames.includes(entry[0] as StateName) && typeof entry[1] === 'number',
96
+ );
97
+ const pending = () => targets.filter(([name, revision]) => !hasApplied(name, revision));
98
+ if (pending().length === 0) return Promise.resolve();
99
+ return new Promise(resolve => {
100
+ const waiter: RevisionWaiter = {
101
+ targets,
102
+ done: () => {
103
+ clearTimeout(timer);
104
+ revisionWaiters.delete(waiter);
105
+ resolve();
106
+ },
107
+ };
108
+ const timer = setTimeout(() => {
109
+ for (const [name] of pending()) logDecodeError('state', name);
110
+ waiter.done();
111
+ }, revisionWaitMillis);
112
+ revisionWaiters.add(waiter);
113
+ });
114
+ }
115
+
116
+ function hasApplied(name: StateName, revision: number): boolean {
117
+ return (appliedRevisions.get(name) ?? -1) >= revision;
118
+ }
119
+
120
+ function settleRevisionWaiters(): void {
121
+ for (const waiter of [...revisionWaiters]) {
122
+ if (waiter.targets.every(([name, revision]) => hasApplied(name, revision))) waiter.done();
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Makes `decoder` the one decoder of `name`, and runs it on the value already held. The bridge
128
+ * calls it with every changed value before any observer; it returns whether it decoded and applied
129
+ * the value, and only then may that value's revision, or a newer one of the same value, satisfy a
130
+ * command's revisions.
131
+ */
132
+ export function decodeState(name: StateName, decoder: (value: unknown) => boolean): void {
133
+ decoders.set(name, decoder);
134
+ const held = states.get(name);
135
+ if (held === undefined) return;
136
+ held.decoded = runDecoder(name, held.value);
137
+ if (held.decoded) markApplied(name, held.revision);
138
+ // It counted on arrival, before the state had a decoder; now it is known to be undecodable.
139
+ else appliedRevisions.delete(name);
140
+ }
141
+
142
+ function runDecoder(name: StateName, value: unknown): boolean {
143
+ const decoder = decoders.get(name);
144
+ if (decoder === undefined) return true;
145
+ try { return decoder(value); }
146
+ catch {
147
+ logDecodeError('state', name);
148
+ return false;
149
+ }
150
+ }
151
+
152
+ function markApplied(name: StateName, revision: number): void {
153
+ appliedRevisions.set(name, revision);
154
+ settleRevisionWaiters();
155
+ }
156
+
157
+ /** Calls `observer` with every new value of `name`, from now on. */
158
+ export function observeState(name: StateName, observer: (value: unknown) => void): () => void {
159
+ let set = observers.get(name);
160
+ if (set === undefined) {
161
+ set = new Set();
162
+ observers.set(name, set);
163
+ }
164
+ const entry = (value: unknown) => observer(value);
165
+ set.add(entry);
166
+ return () => { set.delete(entry); };
167
+ }
168
+
169
+ /**
170
+ * Initialises the native SDK with `configuration` (bridge.md 3.2) and applies the snapshot it
171
+ * replies with before resolving. A native failure rejects with the native error as is.
172
+ */
173
+ export async function initializeBridge(configuration: Record<string, unknown>): Promise<void> {
174
+ subscribe();
175
+ const reply = await Native.initialize(JSON.stringify(configuration));
176
+ const snapshot = parse(reply);
177
+ initialized = true;
178
+ bridgeDidInitialize();
179
+ if (!record(snapshot)) {
180
+ logDecodeError('reply', 'initialize');
181
+ return;
182
+ }
183
+ for (const name of stateNames) {
184
+ const envelope = snapshot[name];
185
+ if (record(envelope)) apply(name, envelope.revision, envelope.value);
186
+ }
187
+ if (Array.isArray(snapshot.passwordRequests)) {
188
+ // A request already answered or cancelled is not taken again.
189
+ for (const request of snapshot.passwordRequests) receivePasswordRequest(request);
190
+ }
191
+ }
192
+
193
+ /** The localised text of an error code, from the native table (works before `initialize`). */
194
+ export function errorMessage(code: string): string {
195
+ if (errorMessages === undefined) {
196
+ const table = parse(Native.getErrorMessages());
197
+ errorMessages = {};
198
+ if (record(table)) {
199
+ for (const [key, value] of Object.entries(table)) {
200
+ if (typeof value === 'string') errorMessages[key] = value;
201
+ }
202
+ }
203
+ }
204
+ return errorMessages[code] ?? '';
205
+ }
206
+
207
+ function subscribe(): void {
208
+ if (subscribed) return;
209
+ subscribed = true;
210
+ Native.onState(receiveState);
211
+ Native.onPasswordRequest(data => receivePasswordRequest(callback('onPasswordRequest', data)));
212
+ Native.onPasswordRequestCancelled(data => receivePasswordRequestCancellation(callback('onPasswordRequestCancelled', data)));
213
+ Native.onPasswordStoreRequest(data => receivePasswordStoreRequest(callback('onPasswordStoreRequest', data)));
214
+ }
215
+
216
+ /** A callback's JSON object; one that is not is logged and handed on as `undefined`. */
217
+ function callback(name: string, data: string): unknown {
218
+ const value = parse(data);
219
+ if (!record(value)) logDecodeError('callback', name);
220
+ return value;
221
+ }
222
+
223
+ function receiveState(data: string): void {
224
+ const update = callback('onState', data);
225
+ if (!record(update) || !stateNames.includes(update.state as StateName)) return;
226
+ apply(update.state as StateName, update.revision, update.value);
227
+ }
228
+
229
+ function apply(name: StateName, revision: unknown, value: unknown): void {
230
+ if (typeof revision !== 'number' || !Number.isSafeInteger(revision) || revision < 0) return;
231
+ const held = states.get(name);
232
+ if (held !== undefined && revision <= held.revision) return;
233
+ const encoded = JSON.stringify(value ?? null);
234
+ const changed = held === undefined || held.encoded !== encoded;
235
+ // A newer revision of the same value is as decoded as the value it repeats.
236
+ const envelope: Envelope = { revision, value: value ?? null, encoded, decoded: changed || held.decoded };
237
+ states.set(name, envelope);
238
+ // Only an actual change reaches the decoder and the observers; a newer revision of the same
239
+ // value does not.
240
+ if (changed) {
241
+ envelope.decoded = runDecoder(name, envelope.value);
242
+ for (const observer of [...(observers.get(name) ?? [])]) {
243
+ try { observer(envelope.value); }
244
+ catch (error) { logListenerError('LV_LISTENER_ERROR', error); }
245
+ }
246
+ }
247
+ // After the observers, so a waiting command resolves with the values already published.
248
+ if (envelope.decoded) markApplied(name, revision);
249
+ }
250
+
251
+ function parse(data: unknown): unknown {
252
+ if (typeof data !== 'string') return undefined;
253
+ try { return JSON.parse(data); }
254
+ catch { return undefined; }
255
+ }
256
+
257
+ export function record(value: unknown): value is Record<string, unknown> {
258
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
259
+ }
@@ -0,0 +1,187 @@
1
+ //===----------------------------------------------------------------------===//
2
+ //
3
+ // This source file is part of the LiveVoice SDK project
4
+ //
5
+ // Copyright (c) LiveVoice GmbH
6
+ // Licensed under the MIT license
7
+ //
8
+ // See LICENSE for license information
9
+ //
10
+ // SPDX-License-Identifier: MIT
11
+ //
12
+ //===----------------------------------------------------------------------===//
13
+
14
+ // The joined event, its requestable languages and its linked events (bridge.md 2.9 to 2.11, 3.3).
15
+ // The lists need the custom-UI permission of the joined key, and so do their commands; native
16
+ // decides both. Their values are observed through Observables.ts.
17
+
18
+ import { awaitRevisions, record } from './Bridge';
19
+ import { invoke, usageError } from './Lifecycle';
20
+
21
+ /** An event's colours, `'#RRGGBB'`, for the light and the dark appearance. */
22
+ export type LiveVoiceBrandColors = {
23
+ light: string;
24
+ dark: string;
25
+ };
26
+
27
+ /** The joined event. */
28
+ export type LiveVoiceEvent = {
29
+ eventId: number;
30
+ name: string;
31
+ /** `null` for an event without branding. */
32
+ brandColors: LiveVoiceBrandColors | null;
33
+ };
34
+
35
+ /**
36
+ * Where a requestable language stands:
37
+ * - `requestable`: it can be requested.
38
+ * - `requested`: a request is on its way, or the server confirmed or accepted it and its channel
39
+ * has not arrived yet. Requests of other listeners count.
40
+ * - `available`: an AI translation of the channel the requests translate exists in that
41
+ * language. A channel translating another channel does not count.
42
+ * - `unavailable`: the event excludes it, because it is spoken on the channel the requests
43
+ * translate.
44
+ */
45
+ export type LiveVoiceLanguageRequestState = 'requestable' | 'requested' | 'available' | 'unavailable';
46
+
47
+ /** A language listeners can ask the event to add. */
48
+ export type LiveVoiceRequestableLanguage = {
49
+ languageCode: string;
50
+ /** The language's name in the device's language. */
51
+ localizedName: string;
52
+ /** The language's name in itself. */
53
+ autonym: string;
54
+ state: LiveVoiceLanguageRequestState;
55
+ };
56
+
57
+ /** An event linked to the joined one, to switch to with {@link switchToLinkedEvent}. */
58
+ export type LiveVoiceLinkedEvent = {
59
+ eventId: number;
60
+ name: string;
61
+ /** The event's join code; it is not secret. */
62
+ joinCode: string;
63
+ };
64
+
65
+ /**
66
+ * Asks the event to add a language and resolves once the server confirmed the request.
67
+ *
68
+ * The language shows `requested` in {@link getCurrentRequestableLanguages} shortly after, and
69
+ * what happens next shows there too. It never starts playback. Needs a `ready` connection and an
70
+ * API key that permits custom UI.
71
+ *
72
+ * @param languageCode - The `languageCode` of a language in state `requestable`.
73
+ * @throws {LiveVoiceError} `not_joined` unless the connection is `ready`; `api_key_invalid`
74
+ * without the custom-UI permission; `invalid_argument` for a code that is unknown or not
75
+ * requestable (also one already requested); `timed_out` when the server does not confirm within
76
+ * 10 seconds (the request may still exist); `network_failed`; `cancelled` when a leave, a new
77
+ * join or a switch ended it; `generic` with `detail.reason` `language_request_declined` or
78
+ * `language_request_failed`. See {@link LiveVoiceErrorCode}.
79
+ */
80
+ export async function requestLanguage(languageCode: string): Promise<void> {
81
+ await invoke('requestLanguage', { languageCode: validCode(languageCode, 'requestLanguage') });
82
+ }
83
+
84
+ /**
85
+ * Withdraws the request for a language and resolves once the server confirmed the cancellation.
86
+ *
87
+ * The language shows `requestable` in {@link getCurrentRequestableLanguages} shortly after. A
88
+ * second cancellation of the same language waits for the first. Needs a `ready` connection and
89
+ * an API key that permits custom UI.
90
+ *
91
+ * @param languageCode - The `languageCode` of a language in state `requested`.
92
+ * @throws {LiveVoiceError} `not_joined` unless the connection is `ready`; `api_key_invalid`
93
+ * without the custom-UI permission; `invalid_argument` for a code that is unknown or not
94
+ * requested; `command_in_progress` while your own request for it is still being sent; `generic`
95
+ * with `detail.reason` `language_request_resolved` when the server decided first; `timed_out`
96
+ * when the server does not confirm within 10 seconds; `network_failed`; `cancelled` when a leave,
97
+ * a new join or a switch ended it; otherwise as {@link requestLanguage}. See
98
+ * {@link LiveVoiceErrorCode}.
99
+ */
100
+ export async function cancelLanguageRequest(languageCode: string): Promise<void> {
101
+ await invoke('cancelLanguageRequest', { languageCode: validCode(languageCode, 'cancelLanguageRequest') });
102
+ }
103
+
104
+ /**
105
+ * Switches to a linked event and resolves once it is ready, with the same guarantees as
106
+ * `joinEvent`. Needs a `ready` connection and an API key that permits custom UI.
107
+ *
108
+ * When the promise resolves, the observed values already show the linked event, or the result of
109
+ * a newer call. Until then the connection is `joining` and the current event and its lists are
110
+ * `null`. After a completed switch the joined event stays valid: its `leave()` leaves the linked
111
+ * event. A leave while the switch is pending ends it with `cancelled` and leaves the event.
112
+ *
113
+ * A failed switch does not return to the previous event: the connection is `failed`, and
114
+ * `reconnect()` tries the linked event again if the error is retryable. The event is not checked
115
+ * against the linked events, so any event you have a join code for works.
116
+ *
117
+ * @param event - The event to switch to, usually one of {@link getCurrentLinkedEvents}.
118
+ * @throws {LiveVoiceError} `not_joined` when no event is ready and no switch is pending, also
119
+ * while reconnecting (the reconnect continues); `api_key_invalid` without the custom-UI
120
+ * permission; `superseded` when a newer switch or join replaced it; `cancelled` when a leave
121
+ * ended it; `timed_out` when the linked event was not ready within 30 seconds; otherwise why the
122
+ * join failed, such as `event_not_found`. See {@link LiveVoiceErrorCode}.
123
+ */
124
+ export async function switchToLinkedEvent(event: LiveVoiceLinkedEvent): Promise<void> {
125
+ if (event == null || typeof event !== 'object' ||
126
+ typeof event.eventId !== 'number' || !Number.isSafeInteger(event.eventId) || event.eventId <= 0 ||
127
+ typeof event.name !== 'string' || typeof event.joinCode !== 'string' || !event.joinCode.trim()) {
128
+ throw usageError('invalid_argument', 'switchToLinkedEvent',
129
+ 'A linked event needs a positive event id, a name and a non-empty join code.');
130
+ }
131
+ const reply = await invoke('switchToLinkedEvent', {
132
+ eventId: event.eventId,
133
+ name: event.name,
134
+ joinCode: event.joinCode,
135
+ });
136
+ // When the switch resolves, the values already show the linked event (18 item 110).
137
+ await awaitRevisions(record(reply) ? reply.revisions : undefined);
138
+ }
139
+
140
+ function validCode(languageCode: string, operation: string): string {
141
+ if (typeof languageCode !== 'string' || !languageCode.trim()) {
142
+ throw usageError('invalid_argument', operation, 'A language code is a non-empty string.');
143
+ }
144
+ return languageCode;
145
+ }
146
+
147
+ // The wire's values (bridge.md 2.9 to 2.11). Each decoder throws for a value it cannot read, so the
148
+ // last good value stays.
149
+
150
+ export function decodeEvent(wire: unknown): LiveVoiceEvent | null {
151
+ if (wire === null) return null;
152
+ if (!record(wire) || typeof wire.eventId !== 'number' || typeof wire.name !== 'string') throw new TypeError('currentEvent');
153
+ const colors = wire.brandColors;
154
+ return {
155
+ eventId: wire.eventId,
156
+ name: wire.name,
157
+ brandColors: record(colors) && typeof colors.light === 'string' && typeof colors.dark === 'string'
158
+ ? { light: colors.light, dark: colors.dark }
159
+ : null,
160
+ };
161
+ }
162
+
163
+ const languageStates: readonly string[] = ['requestable', 'requested', 'available', 'unavailable'];
164
+
165
+ export function decodeLanguages(wire: unknown): LiveVoiceRequestableLanguage[] | null {
166
+ if (wire === null) return null;
167
+ if (!Array.isArray(wire)) throw new TypeError('requestableLanguages');
168
+ return wire.filter(record).flatMap(language =>
169
+ typeof language.languageCode === 'string' && typeof language.localizedName === 'string' &&
170
+ typeof language.autonym === 'string' && typeof language.state === 'string' && languageStates.includes(language.state)
171
+ ? [{
172
+ languageCode: language.languageCode,
173
+ localizedName: language.localizedName,
174
+ autonym: language.autonym,
175
+ state: language.state as LiveVoiceLanguageRequestState,
176
+ }]
177
+ : []);
178
+ }
179
+
180
+ export function decodeLinkedEvents(wire: unknown): LiveVoiceLinkedEvent[] | null {
181
+ if (wire === null) return null;
182
+ if (!Array.isArray(wire)) throw new TypeError('linkedEvents');
183
+ return wire.filter(record).flatMap(event =>
184
+ typeof event.eventId === 'number' && typeof event.name === 'string' && typeof event.joinCode === 'string'
185
+ ? [{ eventId: event.eventId, name: event.name, joinCode: event.joinCode }]
186
+ : []);
187
+ }