@arbidocs/react 0.4.166 → 0.4.168

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 (97) hide show
  1. package/dist/artifacts/index.cjs +15 -12
  2. package/dist/artifacts/index.cjs.map +1 -1
  3. package/dist/artifacts/index.js +6 -3
  4. package/dist/artifacts/index.js.map +1 -1
  5. package/dist/calls/livekit/index.cjs +977 -0
  6. package/dist/calls/livekit/index.cjs.map +1 -0
  7. package/dist/calls/livekit/index.d.cts +280 -0
  8. package/dist/calls/livekit/index.d.ts +280 -0
  9. package/dist/calls/livekit/index.js +961 -0
  10. package/dist/calls/livekit/index.js.map +1 -0
  11. package/dist/{chunk-ON4PL6DQ.cjs → chunk-2M4B4FFA.cjs} +48 -4
  12. package/dist/chunk-2M4B4FFA.cjs.map +1 -0
  13. package/dist/chunk-3J7MEBOW.cjs +2551 -0
  14. package/dist/chunk-3J7MEBOW.cjs.map +1 -0
  15. package/dist/chunk-3NVSUYUV.js +528 -0
  16. package/dist/chunk-3NVSUYUV.js.map +1 -0
  17. package/dist/{chunk-QJHCVQ6C.js → chunk-3WIBD44F.js} +4734 -4673
  18. package/dist/chunk-3WIBD44F.js.map +1 -0
  19. package/dist/chunk-5B4PPJNW.cjs +1035 -0
  20. package/dist/chunk-5B4PPJNW.cjs.map +1 -0
  21. package/dist/chunk-5HDC43MF.js +145 -0
  22. package/dist/chunk-5HDC43MF.js.map +1 -0
  23. package/dist/{chunk-D66JCVBB.cjs → chunk-7NHOKV7N.cjs} +4093 -4040
  24. package/dist/chunk-7NHOKV7N.cjs.map +1 -0
  25. package/dist/chunk-APZZQZ6P.js +147 -0
  26. package/dist/chunk-APZZQZ6P.js.map +1 -0
  27. package/dist/{chunk-I5ZBQ63Y.js → chunk-DGMK3EUN.js} +188 -181
  28. package/dist/chunk-DGMK3EUN.js.map +1 -0
  29. package/dist/chunk-DPYBZDJB.js +18 -0
  30. package/dist/chunk-DPYBZDJB.js.map +1 -0
  31. package/dist/chunk-EEIYXVM4.cjs +181 -0
  32. package/dist/chunk-EEIYXVM4.cjs.map +1 -0
  33. package/dist/chunk-H3LMKO3T.js +2362 -0
  34. package/dist/chunk-H3LMKO3T.js.map +1 -0
  35. package/dist/{chunk-JSSKEXRR.js → chunk-KGCGA452.js} +2 -2
  36. package/dist/chunk-KGCGA452.js.map +1 -0
  37. package/dist/chunk-MJNZLWJD.js +986 -0
  38. package/dist/chunk-MJNZLWJD.js.map +1 -0
  39. package/dist/chunk-N73IMVFF.cjs +21 -0
  40. package/dist/chunk-N73IMVFF.cjs.map +1 -0
  41. package/dist/chunk-NVAIVJID.js +298 -0
  42. package/dist/chunk-NVAIVJID.js.map +1 -0
  43. package/dist/{chunk-GTJ667CP.cjs → chunk-QQ7SCJRY.cjs} +2 -2
  44. package/dist/chunk-QQ7SCJRY.cjs.map +1 -0
  45. package/dist/chunk-S4PCA3ES.cjs +572 -0
  46. package/dist/chunk-S4PCA3ES.cjs.map +1 -0
  47. package/dist/chunk-VAMPYLQ4.cjs +157 -0
  48. package/dist/chunk-VAMPYLQ4.cjs.map +1 -0
  49. package/dist/chunk-VLK52VXC.cjs +307 -0
  50. package/dist/chunk-VLK52VXC.cjs.map +1 -0
  51. package/dist/{chunk-SVHGCX25.js → chunk-YWYCEEBF.js} +43 -4
  52. package/dist/chunk-YWYCEEBF.js.map +1 -0
  53. package/dist/{chunk-EUC2BTNS.cjs → chunk-ZI2VJOID.cjs} +206 -199
  54. package/dist/chunk-ZI2VJOID.cjs.map +1 -0
  55. package/dist/document-tools/index.cjs +85 -109
  56. package/dist/document-tools/index.cjs.map +1 -1
  57. package/dist/document-tools/index.d.cts +19 -5
  58. package/dist/document-tools/index.d.ts +19 -5
  59. package/dist/document-tools/index.js +28 -70
  60. package/dist/document-tools/index.js.map +1 -1
  61. package/dist/index.cjs +12692 -9494
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/{index.d-DfCFKora.d.cts → index.d-Bvp6rKNo.d.cts} +139 -1
  64. package/dist/{index.d-DfCFKora.d.ts → index.d-Bvp6rKNo.d.ts} +139 -1
  65. package/dist/{index.d-DCjYj7YK.d.ts → index.d-Dx9sGkW2.d.cts} +20 -8
  66. package/dist/{index.d-DCjYj7YK.d.cts → index.d-Dx9sGkW2.d.ts} +20 -8
  67. package/dist/index.d.cts +5465 -2291
  68. package/dist/index.d.ts +5465 -2291
  69. package/dist/index.js +11047 -8858
  70. package/dist/index.js.map +1 -1
  71. package/dist/query-keys.d-Kw0JMoff.d.cts +308 -0
  72. package/dist/query-keys.d-Kw0JMoff.d.ts +308 -0
  73. package/dist/shell/index.cjs +78 -21
  74. package/dist/shell/index.d.cts +1 -1
  75. package/dist/shell/index.d.ts +1 -1
  76. package/dist/shell/index.js +6 -1
  77. package/dist/ui/index.cjs +200 -195
  78. package/dist/ui/index.d.cts +1 -1
  79. package/dist/ui/index.d.ts +1 -1
  80. package/dist/ui/index.js +4 -3
  81. package/dist/useAudioRecorder.d-CWFDsb_S.d.cts +778 -0
  82. package/dist/useAudioRecorder.d-CWFDsb_S.d.ts +778 -0
  83. package/dist/viewers/index.cjs +2 -2
  84. package/dist/viewers/index.js +1 -1
  85. package/package.json +13 -3
  86. package/dist/chunk-6MTKKT2O.cjs +0 -999
  87. package/dist/chunk-6MTKKT2O.cjs.map +0 -1
  88. package/dist/chunk-CEZCFQ47.js +0 -932
  89. package/dist/chunk-CEZCFQ47.js.map +0 -1
  90. package/dist/chunk-D66JCVBB.cjs.map +0 -1
  91. package/dist/chunk-EUC2BTNS.cjs.map +0 -1
  92. package/dist/chunk-GTJ667CP.cjs.map +0 -1
  93. package/dist/chunk-I5ZBQ63Y.js.map +0 -1
  94. package/dist/chunk-JSSKEXRR.js.map +0 -1
  95. package/dist/chunk-ON4PL6DQ.cjs.map +0 -1
  96. package/dist/chunk-QJHCVQ6C.js.map +0 -1
  97. package/dist/chunk-SVHGCX25.js.map +0 -1
@@ -0,0 +1,2551 @@
1
+ 'use strict';
2
+
3
+ var chunk5B4PPJNW_cjs = require('./chunk-5B4PPJNW.cjs');
4
+ var chunkVAMPYLQ4_cjs = require('./chunk-VAMPYLQ4.cjs');
5
+ var chunkVLK52VXC_cjs = require('./chunk-VLK52VXC.cjs');
6
+ var chunkEEIYXVM4_cjs = require('./chunk-EEIYXVM4.cjs');
7
+ var chunkQQ7SCJRY_cjs = require('./chunk-QQ7SCJRY.cjs');
8
+ var react = require('react');
9
+ var reactQuery = require('@tanstack/react-query');
10
+ var browser = require('@arbidocs/sdk/browser');
11
+ var client = require('@arbidocs/client');
12
+
13
+ // src/conversation-list.ts
14
+ function isConversationListKey(queryKey) {
15
+ return queryKey.length === 3 && queryKey[0] === "arbi" && queryKey[1] === "conversations";
16
+ }
17
+ var LISTS = {
18
+ predicate: (query) => isConversationListKey(query.queryKey)
19
+ };
20
+ function patchConversationList(queryClient, workspaceId, reducer) {
21
+ if (!workspaceId) return;
22
+ const key = chunkVLK52VXC_cjs.arbiQueryKeys.conversations(workspaceId);
23
+ const current = queryClient.getQueryData(key) ?? [];
24
+ const next = reducer(current);
25
+ if (next !== current) queryClient.setQueryData(key, next);
26
+ }
27
+ function addConversationToList(queryClient, workspaceId, conversation) {
28
+ patchConversationList(queryClient, workspaceId, (old) => [
29
+ conversation,
30
+ ...old.filter((c) => c.external_id !== conversation.external_id)
31
+ ]);
32
+ }
33
+ function patchConversation(queryClient, conversationId, update2) {
34
+ queryClient.setQueriesData(LISTS, (old) => {
35
+ if (!old?.some((c) => c.external_id === conversationId)) return old;
36
+ return old.map(
37
+ (c) => c.external_id === conversationId ? typeof update2 === "function" ? update2(c) : { ...c, ...update2 } : c
38
+ );
39
+ });
40
+ }
41
+ function removeConversationFromLists(queryClient, conversationId) {
42
+ queryClient.setQueriesData(
43
+ LISTS,
44
+ (old) => old?.some((c) => c.external_id === conversationId) ? old.filter((c) => c.external_id !== conversationId) : old
45
+ );
46
+ }
47
+ function invalidateConversationLists(queryClient) {
48
+ return queryClient.invalidateQueries(LISTS);
49
+ }
50
+ function findConversation(queryClient, conversationId) {
51
+ if (!conversationId) return void 0;
52
+ for (const [, list] of queryClient.getQueriesData(LISTS)) {
53
+ const row = list?.find((c) => c.external_id === conversationId);
54
+ if (row) return row;
55
+ }
56
+ return void 0;
57
+ }
58
+ function isConversationShared(queryClient, conversationId) {
59
+ return findConversation(queryClient, conversationId)?.is_shared ?? false;
60
+ }
61
+ function isKnownSoloConversation(queryClient, conversationId) {
62
+ const row = findConversation(queryClient, conversationId);
63
+ return row !== void 0 && !row.is_shared;
64
+ }
65
+ function invalidateConversationDetails(queryClient, conversationId) {
66
+ return queryClient.invalidateQueries({
67
+ predicate: ({ queryKey }) => queryKey[0] === "arbi" && queryKey[1] === "conversations" && queryKey[2] === conversationId && queryKey[3] !== "threads"
68
+ });
69
+ }
70
+ var ArbiWsContext = react.createContext(null);
71
+ function useArbiWsContext() {
72
+ const ctx = react.useContext(ArbiWsContext);
73
+ if (!ctx) {
74
+ throw new Error("useArbiWebSocket hooks must be used within an <ArbiWebSocketProvider>");
75
+ }
76
+ return ctx;
77
+ }
78
+ function toProfileView(profile) {
79
+ return {
80
+ ...profile,
81
+ fullName: [profile.givenName, profile.familyName].map((part) => part?.trim()).filter(Boolean).join(" ")
82
+ };
83
+ }
84
+ function useProfile(options) {
85
+ const { client, enabled } = useAccountClient();
86
+ const qc = reactQuery.useQueryClient();
87
+ react.useEffect(
88
+ () => client.onProfileChange(() => qc.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.profile(), client.profile())),
89
+ [client, qc]
90
+ );
91
+ return reactQuery.useQuery({
92
+ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.profile(),
93
+ queryFn: () => client.profile(),
94
+ enabled: (options?.enabled ?? true) && enabled,
95
+ staleTime: Infinity
96
+ });
97
+ }
98
+ function useUpdateProfile() {
99
+ const { client } = useAccountClient();
100
+ const qc = reactQuery.useQueryClient();
101
+ return reactQuery.useMutation({
102
+ mutationFn: async (vars) => {
103
+ await client.updateProfile(vars);
104
+ return client.profile();
105
+ },
106
+ onSuccess: (profile) => {
107
+ qc.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.profile(), profile);
108
+ void qc.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.identity() });
109
+ return qc.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.workspaces() });
110
+ }
111
+ });
112
+ }
113
+ function useNameEditor({ givenName, familyName, save }) {
114
+ const [isEditing, setIsEditing] = react.useState(false);
115
+ const [given, setGiven] = react.useState("");
116
+ const [family, setFamily] = react.useState("");
117
+ const [isSaving, setIsSaving] = react.useState(false);
118
+ const [error, setError] = react.useState(null);
119
+ const onStartEdit = react.useCallback(() => {
120
+ setGiven(givenName ?? "");
121
+ setFamily(familyName ?? "");
122
+ setError(null);
123
+ setIsEditing(true);
124
+ }, [givenName, familyName]);
125
+ const onSave = react.useCallback(() => {
126
+ const trimmedGiven = given.trim();
127
+ if (!trimmedGiven) return;
128
+ setIsSaving(true);
129
+ setError(null);
130
+ void Promise.resolve().then(() => save({ givenName: trimmedGiven, familyName: family.trim() })).then(() => setIsEditing(false)).catch((e) => setError(e)).finally(() => setIsSaving(false));
131
+ }, [given, family, save]);
132
+ return {
133
+ isEditing,
134
+ givenName: given,
135
+ familyName: family,
136
+ onGivenNameChange: setGiven,
137
+ onFamilyNameChange: setFamily,
138
+ onStartEdit,
139
+ onSave,
140
+ onCancel: () => setIsEditing(false),
141
+ isSaving,
142
+ error
143
+ };
144
+ }
145
+ var MAX_AVATAR_FILE_BYTES = 5 * 1024 * 1024;
146
+ function useAvatarCrop({
147
+ upload,
148
+ onProblem,
149
+ maxBytes = MAX_AVATAR_FILE_BYTES
150
+ }) {
151
+ const [pendingImage, setPendingImage] = react.useState(null);
152
+ const [isUploading, setIsUploading] = react.useState(false);
153
+ const onFileChosen = react.useCallback(
154
+ (file) => {
155
+ if (!file.type.startsWith("image/")) return onProblem?.("not-image");
156
+ if (file.size > maxBytes) return onProblem?.("too-large");
157
+ const reader = new FileReader();
158
+ reader.onload = () => setPendingImage(reader.result);
159
+ reader.onerror = () => onProblem?.("unreadable");
160
+ reader.readAsDataURL(file);
161
+ },
162
+ [maxBytes, onProblem]
163
+ );
164
+ const onCropComplete = react.useCallback(
165
+ (result) => {
166
+ setPendingImage(null);
167
+ setIsUploading(true);
168
+ void Promise.resolve().then(() => upload(result.dataUrl)).catch(() => {
169
+ }).finally(() => setIsUploading(false));
170
+ },
171
+ [upload]
172
+ );
173
+ return {
174
+ onFileChosen,
175
+ pendingImage,
176
+ onCropComplete,
177
+ onCropCancel: () => setPendingImage(null),
178
+ isUploading
179
+ };
180
+ }
181
+
182
+ // src/account/client.tsx
183
+ function arbiProfile(arbi) {
184
+ const profile = arbi.user.profile();
185
+ return profile ? toProfileView(profile) : null;
186
+ }
187
+ function arbiAccountClient(arbi, overrides = {}) {
188
+ return {
189
+ profile: () => arbiProfile(arbi),
190
+ onProfileChange: (listener) => arbi.user.onProfileChange(() => listener()),
191
+ updateProfile: async (vars) => {
192
+ await arbi.profile.update({
193
+ ...vars.givenName !== void 0 && { given_name: vars.givenName.trim() },
194
+ ...vars.familyName !== void 0 && { family_name: vars.familyName.trim() },
195
+ ...vars.picture !== void 0 && { picture: vars.picture }
196
+ });
197
+ },
198
+ requestEmailChange: (newEmail) => arbi.account.requestEmailChange(newEmail),
199
+ confirmEmailChange: async (newEmail, code) => {
200
+ await arbi.account.confirmEmailChange(newEmail, code);
201
+ },
202
+ changePassword: (vars) => arbi.account.changePassword(vars),
203
+ listSessions: () => arbi.sessions.list(),
204
+ currentSessionId: () => arbi.sessions.currentId(),
205
+ terminateSession: (sessionId) => arbi.sessions.terminate(sessionId),
206
+ signOut: async ({ everywhere } = {}) => {
207
+ try {
208
+ if (everywhere) await arbi.sessions.logoutAll();
209
+ else await arbi.logout();
210
+ } finally {
211
+ chunk5B4PPJNW_cjs.clearSealedDrafts();
212
+ }
213
+ },
214
+ requestDeletion: () => arbi.account.requestDeletion(),
215
+ identity: {
216
+ status: () => arbi.identity.status(),
217
+ purchase: () => arbi.identity.purchase(),
218
+ startSession: () => arbi.identity.startSession(),
219
+ refresh: () => arbi.identity.refresh(),
220
+ acceptName: () => arbi.identity.acceptName(),
221
+ remove: () => arbi.identity.remove()
222
+ },
223
+ ...overrides
224
+ };
225
+ }
226
+ var NO_ACCOUNT_ERROR = "The account needs an <ArbiHost> with `account` or an `arbi`";
227
+ var refuse = () => Promise.reject(new Error(NO_ACCOUNT_ERROR));
228
+ var NO_ACCOUNT = {
229
+ client: {
230
+ profile: () => null,
231
+ onProfileChange: () => () => {
232
+ },
233
+ updateProfile: refuse,
234
+ requestEmailChange: refuse,
235
+ confirmEmailChange: refuse,
236
+ changePassword: refuse,
237
+ listSessions: refuse,
238
+ currentSessionId: () => null,
239
+ terminateSession: refuse,
240
+ signOut: refuse,
241
+ requestDeletion: refuse,
242
+ identity: {
243
+ status: refuse,
244
+ purchase: refuse,
245
+ startSession: refuse,
246
+ refresh: refuse,
247
+ acceptName: refuse,
248
+ remove: refuse
249
+ }
250
+ },
251
+ enabled: false
252
+ };
253
+ var ALWAYS = () => true;
254
+ function useAccountClient() {
255
+ const { account, arbi } = chunkQQ7SCJRY_cjs.useArbiHost();
256
+ const fallback = react.useMemo(() => arbi ? arbiAccountClient(arbi) : null, [arbi]);
257
+ const useEnabled = account?.useEnabled ?? ALWAYS;
258
+ const enabled = useEnabled();
259
+ const client = account?.client;
260
+ const provided = react.useMemo(() => client ? { client, enabled } : null, [client, enabled]);
261
+ if (provided) return provided;
262
+ if (!arbi || !fallback) return NO_ACCOUNT;
263
+ return { client: fallback, enabled: arbi.isLoggedIn };
264
+ }
265
+ function useEntitlements() {
266
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
267
+ return reactQuery.useQuery({
268
+ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.entitlements(),
269
+ queryFn: () => arbi.account.entitlements(),
270
+ enabled: arbi.isLoggedIn,
271
+ // A plan change shows on the next read; the API enforces it at once either way.
272
+ staleTime: 5 * 60 * 1e3
273
+ });
274
+ }
275
+ function useIsEntitled(feature) {
276
+ const { data } = useEntitlements();
277
+ return data?.[feature] === true;
278
+ }
279
+ function entitlementRefusal(reason) {
280
+ switch (reason) {
281
+ case "external_user":
282
+ return {
283
+ title: "Not available for external users",
284
+ description: "Mail, Calendar and hosting calls are for members of the firm. You can still join calls others host."
285
+ };
286
+ case "not_entitled":
287
+ return {
288
+ title: "Not available on this account",
289
+ description: "Mail, Calendar and hosting calls are not available on this account."
290
+ };
291
+ default:
292
+ return {
293
+ title: "Available on Pro",
294
+ description: "Mail, Calendar and hosting calls come with a Pro plan. You can still join calls others host."
295
+ };
296
+ }
297
+ }
298
+
299
+ // src/calls/keys.ts
300
+ function invalidateCall(queryClient, message) {
301
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.callQueryKeys.call(message.call_ext_id) });
302
+ const thread = message.log_conversation_ext_id;
303
+ if (thread) {
304
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.conversationActivity(thread) });
305
+ }
306
+ }
307
+ function myChatId(arbi) {
308
+ try {
309
+ return arbi.user.identity()?.externalId ?? null;
310
+ } catch {
311
+ return null;
312
+ }
313
+ }
314
+ var openChatExtId = null;
315
+ function setOpenChat(chatExtId) {
316
+ openChatExtId = chatExtId;
317
+ }
318
+ function getOpenChat() {
319
+ return openChatExtId;
320
+ }
321
+ function byActivity(a, b) {
322
+ const at = Date.parse(a.last_message_at ?? a.created_at);
323
+ const bt = Date.parse(b.last_message_at ?? b.created_at);
324
+ return bt - at;
325
+ }
326
+ function cachedChats(queryClient) {
327
+ return queryClient.getQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatList()) ?? [];
328
+ }
329
+ function cachedChat(queryClient, chatExtId) {
330
+ return cachedChats(queryClient).find((c) => c.external_id === chatExtId);
331
+ }
332
+ function upsertChat(queryClient, chat) {
333
+ queryClient.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatList(), (old) => {
334
+ if (!old) return old;
335
+ const rest = old.filter((c) => c.external_id !== chat.external_id);
336
+ return [chat, ...rest].sort(byActivity);
337
+ });
338
+ }
339
+ function removeChat(queryClient, chatExtId) {
340
+ queryClient.setQueryData(
341
+ chunkVLK52VXC_cjs.arbiQueryKeys.chatList(),
342
+ (old) => old?.filter((c) => c.external_id !== chatExtId)
343
+ );
344
+ queryClient.removeQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId) });
345
+ }
346
+ function appendToThread(queryClient, chatExtId, message, replaceOptimisticId) {
347
+ queryClient.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId), (old) => {
348
+ if (!old) return old;
349
+ const without = old.messages.filter(
350
+ (m) => m.external_id !== message.external_id && m.external_id !== replaceOptimisticId
351
+ );
352
+ return { ...old, messages: [...without, message] };
353
+ });
354
+ }
355
+ function dropFromThread(queryClient, chatExtId, messageExtId) {
356
+ queryClient.setQueryData(
357
+ chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId),
358
+ (old) => old ? { ...old, messages: old.messages.filter((m) => m.external_id !== messageExtId) } : old
359
+ );
360
+ }
361
+ function replaceInThread(queryClient, chatExtId, message) {
362
+ queryClient.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId), (old) => {
363
+ if (!old || !old.messages.some((m) => m.external_id === message.external_id)) return old;
364
+ return {
365
+ ...old,
366
+ messages: old.messages.map((m) => m.external_id === message.external_id ? message : m)
367
+ };
368
+ });
369
+ }
370
+ function patchLastMessage(queryClient, chatExtId, message) {
371
+ queryClient.setQueryData(
372
+ chunkVLK52VXC_cjs.arbiQueryKeys.chatList(),
373
+ (old) => old?.map(
374
+ (c) => c.external_id === chatExtId && c.last_message?.external_id === message.external_id ? { ...c, last_message: message } : c
375
+ )
376
+ );
377
+ }
378
+ async function deleteChatMessage(arbi, queryClient, chatExtId, messageExtId) {
379
+ const thread = queryClient.getQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId));
380
+ const before = thread?.messages.find((m) => m.external_id === messageExtId);
381
+ const listed = cachedChat(queryClient, chatExtId);
382
+ const wasLast = listed?.last_message?.external_id === messageExtId ? listed.last_message : null;
383
+ if (before) replaceInThread(queryClient, chatExtId, browser.chats.chatMessageTombstone(before));
384
+ if (wasLast) patchLastMessage(queryClient, chatExtId, browser.chats.chatMessageTombstone(wasLast));
385
+ try {
386
+ await arbi.chats.deleteMessage(chatExtId, messageExtId);
387
+ } catch (err) {
388
+ if (before) replaceInThread(queryClient, chatExtId, before);
389
+ if (wasLast) patchLastMessage(queryClient, chatExtId, wasLast);
390
+ throw err;
391
+ }
392
+ }
393
+ async function applyChangedMessage(arbi, queryClient, chatExtId, message) {
394
+ if (message.deleted) {
395
+ replaceInThread(queryClient, chatExtId, browser.chats.chatMessageTombstone(message));
396
+ patchLastMessage(queryClient, chatExtId, browser.chats.chatMessageTombstone(message));
397
+ return;
398
+ }
399
+ const chat = cachedChat(queryClient, chatExtId);
400
+ if (!chat || !queryClient.getQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId))) return;
401
+ try {
402
+ replaceInThread(queryClient, chatExtId, await arbi.chats.decrypt(chat, message));
403
+ } catch (err) {
404
+ console.error("[chats] could not decrypt a changed message", err);
405
+ }
406
+ }
407
+ async function applyChatMessage(arbi, queryClient, chatExtId, message) {
408
+ if (message.deleted) return applyChangedMessage(arbi, queryClient, chatExtId, message);
409
+ const me = myChatId(arbi);
410
+ const chat = cachedChat(queryClient, chatExtId);
411
+ if (!chat) {
412
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.chatList() });
413
+ return;
414
+ }
415
+ const mine = message.sender_ext_id === me;
416
+ const isOpen = openChatExtId === chatExtId;
417
+ upsertChat(queryClient, {
418
+ ...chat,
419
+ last_message: message,
420
+ last_message_at: message.created_at,
421
+ unread_count: mine ? 0 : isOpen ? chat.unread_count : chat.unread_count + 1,
422
+ members: mine ? chat.members.map(
423
+ (m) => m.user.external_id === me ? { ...m, last_read_at: message.created_at } : m
424
+ ) : chat.members
425
+ });
426
+ if (queryClient.getQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId))) {
427
+ try {
428
+ appendToThread(queryClient, chatExtId, await arbi.chats.decrypt(chat, message));
429
+ } catch (err) {
430
+ console.error("[chats] could not decrypt a live message", err);
431
+ }
432
+ }
433
+ }
434
+ function applyChatRead(arbi, queryClient, chatExtId, userExtId, lastReadAt) {
435
+ const me = myChatId(arbi);
436
+ queryClient.setQueryData(
437
+ chunkVLK52VXC_cjs.arbiQueryKeys.chatList(),
438
+ (old) => old?.map(
439
+ (c) => c.external_id !== chatExtId ? c : {
440
+ ...c,
441
+ unread_count: userExtId === me ? 0 : c.unread_count,
442
+ members: c.members.map(
443
+ (m) => m.user.external_id === userExtId ? { ...m, last_read_at: lastReadAt } : m
444
+ )
445
+ }
446
+ )
447
+ );
448
+ }
449
+ async function applyChatUpdated(arbi, queryClient, chatExtId, message) {
450
+ if (message) await applyChangedMessage(arbi, queryClient, chatExtId, message);
451
+ let chat;
452
+ try {
453
+ chat = await arbi.chats.get(chatExtId);
454
+ } catch {
455
+ removeChat(queryClient, chatExtId);
456
+ return;
457
+ }
458
+ if (chat.rotation_required) {
459
+ chat = await arbi.chats.ready(chat).catch(() => chat);
460
+ }
461
+ upsertChat(queryClient, chat);
462
+ if (!message)
463
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.chatThread(chatExtId) });
464
+ }
465
+ function applyAgentDmStatus(queryClient, status) {
466
+ if (!["queued", "working", "done", "failed"].includes(status.status)) return;
467
+ queryClient.setQueryData(chunkVLK52VXC_cjs.arbiQueryKeys.agentDmStatus(status.agent_ext_id), status);
468
+ }
469
+ async function applyChatEvent(arbi, queryClient, event) {
470
+ const e = event;
471
+ if (e.type === "chat.message")
472
+ return applyChatMessage(arbi, queryClient, e.chat_ext_id, e.message);
473
+ if (e.type === "chat.read")
474
+ return applyChatRead(arbi, queryClient, e.chat_ext_id, e.user_ext_id, e.last_read_at);
475
+ if (e.type === "chat.updated")
476
+ return applyChatUpdated(arbi, queryClient, e.chat_ext_id, e.message);
477
+ if (e.type === "agent_dm_status") applyAgentDmStatus(queryClient, e);
478
+ }
479
+ function meetingChatRefFrom(row) {
480
+ if (row.chat_ext_id) return { kind: "chat", chatExtId: row.chat_ext_id };
481
+ const workspaceExtId = row.workspace_ext_id ?? row.locked_workspace_ext_id;
482
+ if (row.meeting_conversation_ext_id && workspaceExtId) {
483
+ return {
484
+ kind: "thread",
485
+ conversationExtId: row.meeting_conversation_ext_id,
486
+ workspaceExtId
487
+ };
488
+ }
489
+ return null;
490
+ }
491
+ function callMemberKeys(call) {
492
+ const keys = /* @__PURE__ */ new Map();
493
+ if (call.creator_ext_id && call.creator_encryption_public_key) {
494
+ keys.set(call.creator_ext_id, call.creator_encryption_public_key);
495
+ }
496
+ for (const i of call.invitees ?? []) {
497
+ if (i.encryption_public_key) keys.set(i.user_ext_id, i.encryption_public_key);
498
+ }
499
+ return keys;
500
+ }
501
+ async function publicKeysFor(arbi, queryClient, userExtIds, known) {
502
+ const wanted = new Set(userExtIds);
503
+ const keys = new Map([...known].filter(([id]) => wanted.has(id)));
504
+ if (![...wanted].some((id) => !keys.has(id))) return keys;
505
+ for (const chat of cachedChats(queryClient)) {
506
+ for (const m of chat.members) {
507
+ if (wanted.has(m.user.external_id) && !keys.has(m.user.external_id) && m.user.encryption_public_key) {
508
+ keys.set(m.user.external_id, m.user.encryption_public_key);
509
+ }
510
+ }
511
+ }
512
+ if ([...wanted].some((id) => !keys.has(id))) {
513
+ try {
514
+ for (const c of await arbi.contacts.list()) {
515
+ const u = c.user;
516
+ if (u && wanted.has(u.external_id) && u.encryption_public_key && !keys.has(u.external_id)) {
517
+ keys.set(u.external_id, u.encryption_public_key);
518
+ }
519
+ }
520
+ } catch (err) {
521
+ console.warn("[calls] could not load contacts for the meeting chat", err);
522
+ }
523
+ }
524
+ return keys;
525
+ }
526
+ async function buildMeetingChatBody(arbi, queryClient, call, callKey, extraMembers = []) {
527
+ if (!arbi.isLoggedIn) throw new Error("Sign in to keep the meeting chat");
528
+ const { externalId: me, publicKey: myPublicKey } = await arbi.chats.identity();
529
+ const hosts = /* @__PURE__ */ new Set([
530
+ call.creator_ext_id,
531
+ ...(call.invitees ?? []).map((i) => i.user_ext_id)
532
+ ]);
533
+ const memberIds = [.../* @__PURE__ */ new Set([...hosts, ...extraMembers])].filter(
534
+ (id) => id && id !== me && !browser.chats.isAgentExtId(id)
535
+ );
536
+ const pubKeys = await publicKeysFor(arbi, queryClient, memberIds, callMemberKeys(call));
537
+ const key = await client.generateChatKey();
538
+ try {
539
+ const members = [];
540
+ for (const id of memberIds) {
541
+ const pk = pubKeys.get(id);
542
+ if (!pk) {
543
+ console.warn("[calls] no public key for meeting-chat member", id);
544
+ continue;
545
+ }
546
+ members.push({
547
+ user_ext_id: id,
548
+ sealed_key: await client.sealChatKey(key, pk),
549
+ ...hosts.has(id) ? {} : { call_sealed_key: await client.sealCallKey(callKey, pk) }
550
+ });
551
+ }
552
+ const title = call.title ? await client.decryptCallTitle(call.title, callKey) : null;
553
+ return {
554
+ title: await client.encryptWithChatKey(title?.trim() || "Meeting", key),
555
+ creator_sealed_key: await client.sealChatKey(key, myPublicKey),
556
+ members
557
+ };
558
+ } finally {
559
+ key.fill(0);
560
+ }
561
+ }
562
+ var pending = /* @__PURE__ */ new Map();
563
+ function ensureMeetingChat(arbi, queryClient, callExtId, callKey) {
564
+ const inFlight = pending.get(callExtId);
565
+ if (inFlight) return inFlight;
566
+ const run = (async () => {
567
+ const call = await arbi.calls.get(callExtId);
568
+ const existing = meetingChatRefFrom(call);
569
+ if (existing) return existing;
570
+ const body = call.workspace_locked ? void 0 : await buildMeetingChatBody(arbi, queryClient, call, callKey);
571
+ const answer = await arbi.calls.chat(callExtId, body);
572
+ const ref = meetingChatRefFrom({
573
+ ...answer,
574
+ locked_workspace_ext_id: call.locked_workspace_ext_id
575
+ });
576
+ if (!ref) throw new Error("The server did not return a meeting chat");
577
+ if (ref.kind === "chat")
578
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.arbiQueryKeys.chatList() });
579
+ else void invalidateConversationLists(queryClient);
580
+ return ref;
581
+ })();
582
+ pending.set(callExtId, run);
583
+ run.catch(() => pending.delete(callExtId));
584
+ return run;
585
+ }
586
+ function clearMeetingChatCache() {
587
+ pending.clear();
588
+ }
589
+ function knownMeetingChat(target) {
590
+ if (target.chatExtId) return { kind: "chat", chatExtId: target.chatExtId };
591
+ if (target.meetingConversationExtId && target.workspaceExtId) {
592
+ return {
593
+ kind: "thread",
594
+ conversationExtId: target.meetingConversationExtId,
595
+ workspaceExtId: target.workspaceExtId
596
+ };
597
+ }
598
+ return null;
599
+ }
600
+ async function resolveMeetingChat(arbi, queryClient, target) {
601
+ const known = knownMeetingChat(target);
602
+ if (known) return known;
603
+ const key = target.callKey ?? await arbi.calls.key(await arbi.calls.get(target.callExtId));
604
+ if (!key) throw new Error("You are not invited to this call");
605
+ return ensureMeetingChat(arbi, queryClient, target.callExtId, key);
606
+ }
607
+ function sortTranscriptMessages(messages) {
608
+ const spokenAt = (m) => {
609
+ const parsed = m.decryptFailed ? null : browser.chats.parseTranscriptContent(m.content);
610
+ const at = Date.parse(parsed?.started_at ?? m.created_at);
611
+ return Number.isNaN(at) ? 0 : at;
612
+ };
613
+ return messages.map((m, i) => ({ m, i, at: spokenAt(m) })).sort((a, b) => a.at - b.at || a.i - b.i).map(({ m }) => m);
614
+ }
615
+ function transcriptSegmentOf(tools) {
616
+ if (!tools || typeof tools !== "object") return void 0;
617
+ const record = tools;
618
+ const byKey = record.transcript_segment;
619
+ const candidates = byKey ? [byKey] : Object.values(record);
620
+ for (const c of candidates) {
621
+ if (!c || typeof c !== "object") continue;
622
+ const t = c;
623
+ if (c !== byKey && t.name !== "transcript_segment") continue;
624
+ if (typeof t.segment_id !== "string" || typeof t.speaker_ext_id !== "string") continue;
625
+ return {
626
+ segment_id: t.segment_id,
627
+ speaker_ext_id: t.speaker_ext_id,
628
+ started_at: typeof t.started_at === "string" ? t.started_at : null
629
+ };
630
+ }
631
+ return void 0;
632
+ }
633
+ var pad = (n) => String(n).padStart(2, "0");
634
+ function clockTime(iso) {
635
+ if (!iso) return "";
636
+ const d = new Date(iso);
637
+ if (Number.isNaN(d.getTime())) return "";
638
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
639
+ }
640
+ function formatTranscriptMarkdown(opts) {
641
+ const lines = [...opts.lines].filter((l) => l.text.trim()).sort((a, b) => (Date.parse(a.at ?? "") || 0) - (Date.parse(b.at ?? "") || 0));
642
+ const first = lines.find((l) => l.at)?.at;
643
+ const date = opts.date ?? (first ? new Date(first) : null);
644
+ const heading = `## Transcript: ${opts.title?.trim() || "Meeting"}`;
645
+ const dateLine = date ? `_${date.toLocaleDateString(void 0, { year: "numeric", month: "long", day: "numeric" })}_` : null;
646
+ const body = lines.map((l) => {
647
+ const time = clockTime(l.at);
648
+ return `**${l.speaker}**${time ? ` [${time}]` : ""}: ${l.text.trim().replace(/\s*\n\s*/g, " ")}`;
649
+ });
650
+ return [heading, ...dateLine ? [dateLine] : [], ...body].join("\n\n");
651
+ }
652
+ function threadTranscriptLines(messages, nameOf) {
653
+ const seen = /* @__PURE__ */ new Set();
654
+ const lines = [];
655
+ for (const m of messages) {
656
+ const marker = transcriptSegmentOf(m.tools);
657
+ if (!marker || seen.has(marker.segment_id)) continue;
658
+ seen.add(marker.segment_id);
659
+ const name = nameOf(marker.speaker_ext_id);
660
+ lines.push({
661
+ speaker: name || "Former member",
662
+ at: marker.started_at ?? m.created_at ?? null,
663
+ text: stripSpeakerPrefix(m.content ?? "", name)
664
+ });
665
+ }
666
+ return lines;
667
+ }
668
+ function stripSpeakerPrefix(content, speakerName) {
669
+ if (speakerName && content.startsWith(`${speakerName}: `)) {
670
+ return content.slice(speakerName.length + 2);
671
+ }
672
+ return content;
673
+ }
674
+ function isRecordingSegmentId(segmentId) {
675
+ return typeof segmentId === "string" && segmentId.startsWith("rec-");
676
+ }
677
+ function recordingWindowsOf(recordings) {
678
+ return recordings.map((r) => ({
679
+ trackExtIds: (r.tracks ?? []).map((t) => t.external_id),
680
+ startedAt: r.started_at,
681
+ stoppedAt: r.stopped_at ?? null
682
+ }));
683
+ }
684
+ function chatTranscriptRef(message) {
685
+ if (!browser.chats.isTranscriptMessage(message)) return null;
686
+ const parsed = message.decryptFailed ? null : browser.chats.parseTranscriptContent(message.content);
687
+ return { segmentId: message.dedupe_key, startedAt: parsed?.started_at ?? message.created_at };
688
+ }
689
+ function threadTranscriptRef(message) {
690
+ const marker = transcriptSegmentOf(message.tools ?? message.meta?.tools);
691
+ if (!marker) return null;
692
+ return { segmentId: marker.segment_id, startedAt: marker.started_at ?? message.created_at };
693
+ }
694
+ function supersededTranscriptLines(lines, refOf, recordings = []) {
695
+ const superseded = /* @__PURE__ */ new Set();
696
+ const recLines = [];
697
+ for (const line of lines) {
698
+ const ref = refOf(line);
699
+ if (ref && isRecordingSegmentId(ref.segmentId)) {
700
+ recLines.push({ segmentId: ref.segmentId, at: Date.parse(ref.startedAt ?? "") });
701
+ }
702
+ }
703
+ if (!recLines.length) return superseded;
704
+ const windows = [];
705
+ const claimed = /* @__PURE__ */ new Set();
706
+ for (const r of recordings) {
707
+ const prefixes = r.trackExtIds.map((t) => `rec-${t}-`);
708
+ const mine = recLines.filter((l) => prefixes.some((p) => l.segmentId.startsWith(p)));
709
+ if (!mine.length) continue;
710
+ for (const l of mine) claimed.add(l.segmentId);
711
+ const start = Date.parse(r.startedAt);
712
+ const stop = r.stoppedAt ? Date.parse(r.stoppedAt) : Number.POSITIVE_INFINITY;
713
+ if (!Number.isNaN(start)) windows.push([start, Number.isNaN(stop) ? Infinity : stop]);
714
+ }
715
+ const unclaimed = recLines.filter((l) => !claimed.has(l.segmentId) && !Number.isNaN(l.at));
716
+ if (unclaimed.length) {
717
+ const times = unclaimed.map((l) => l.at);
718
+ windows.push([Math.min(...times), Math.max(...times)]);
719
+ }
720
+ if (!windows.length) return superseded;
721
+ for (const line of lines) {
722
+ const ref = refOf(line);
723
+ if (!ref || isRecordingSegmentId(ref.segmentId)) continue;
724
+ const at = Date.parse(ref.startedAt ?? "");
725
+ if (Number.isNaN(at)) continue;
726
+ if (windows.some(([start, stop]) => at >= start && at <= stop)) superseded.add(line);
727
+ }
728
+ return superseded;
729
+ }
730
+ function supersedeLiveTranscript(lines, refOf, recordings = []) {
731
+ const superseded = supersededTranscriptLines(lines, refOf, recordings);
732
+ return superseded.size ? lines.filter((l) => !superseded.has(l)) : [...lines];
733
+ }
734
+ function hasRecordingTranscript(lines, refOf) {
735
+ return lines.some((l) => isRecordingSegmentId(refOf(l)?.segmentId));
736
+ }
737
+ var CALL_CHAT_TOPIC = "arbi.chat";
738
+ var READ_ONLY_MEETING_TEXT = "Read-only: workspace guests can\u2019t post";
739
+ var CALL_CHAT_MAX_CHARS = 4e3;
740
+ var encoder = new TextEncoder();
741
+ var decoder = new TextDecoder();
742
+ function newPacketId() {
743
+ const bytes = new Uint8Array(8);
744
+ globalThis.crypto.getRandomValues(bytes);
745
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
746
+ }
747
+ async function encodeCallChatPacket(packet, callKey) {
748
+ return encoder.encode(await client.encryptWithChatKey(JSON.stringify(packet), callKey));
749
+ }
750
+ async function decodeCallChatPacket(payload, callKey) {
751
+ try {
752
+ const parsed = JSON.parse(await client.decryptWithChatKey(decoder.decode(payload), callKey));
753
+ if (!parsed || typeof parsed !== "object") return null;
754
+ const p = parsed;
755
+ if (p.v !== 1 || typeof p.id !== "string" || typeof p.text !== "string") return null;
756
+ const text = p.text.slice(0, CALL_CHAT_MAX_CHARS);
757
+ if (!text.trim()) return null;
758
+ return { v: 1, id: p.id, text, at: typeof p.at === "number" ? p.at : Date.now() };
759
+ } catch {
760
+ return null;
761
+ }
762
+ }
763
+ async function chatByExtId(arbi, queryClient, chatExtId) {
764
+ return cachedChat(queryClient, chatExtId) ?? arbi.chats.get(chatExtId);
765
+ }
766
+ async function persistMeetingMessage(arbi, queryClient, callExtId, callKey, text) {
767
+ const ref = await ensureMeetingChat(arbi, queryClient, callExtId, callKey);
768
+ if (ref.kind === "chat") {
769
+ await arbi.chats.send(await chatByExtId(arbi, queryClient, ref.chatExtId), text);
770
+ } else {
771
+ try {
772
+ await arbi.conversations.postMessage({
773
+ content: text,
774
+ conversation_ext_id: ref.conversationExtId,
775
+ assistant_mode: "mentioned"
776
+ });
777
+ } catch (err) {
778
+ const status = err instanceof browser.ArbiApiError ? err.status : void 0;
779
+ const detail = err instanceof browser.ArbiApiError ? err.detail : void 0;
780
+ throw new Error(
781
+ `Could not save the message to the meeting thread (${status ?? "?"})${detail ? `: ${detail}` : ""}`
782
+ );
783
+ }
784
+ }
785
+ return ref;
786
+ }
787
+ var HISTORY_LIMIT = 50;
788
+ async function loadMeetingHistory(arbi, queryClient, callExtId) {
789
+ const ref = meetingChatRefFrom(await arbi.calls.get(callExtId));
790
+ if (!ref) return null;
791
+ if (ref.kind === "chat") {
792
+ const chat = await chatByExtId(arbi, queryClient, ref.chatExtId);
793
+ const page = await arbi.chats.page(chat);
794
+ const names = new Map(chat.members.map((m) => [m.user.external_id, chunkEEIYXVM4_cjs.getUserDisplayName(m.user)]));
795
+ return {
796
+ ref,
797
+ messages: page.messages.filter((m) => m.kind === "text" && !m.decryptFailed && m.content).slice(-HISTORY_LIMIT).map((m) => ({
798
+ id: m.external_id,
799
+ senderExtId: m.sender_ext_id ?? null,
800
+ senderName: m.sender_ext_id && names.get(m.sender_ext_id) || null,
801
+ text: m.content ?? "",
802
+ at: Date.parse(m.created_at)
803
+ }))
804
+ };
805
+ }
806
+ const data = await arbi.conversations.getThreads(ref.conversationExtId).catch(() => null);
807
+ if (!data) return { ref, messages: [] };
808
+ const seen = /* @__PURE__ */ new Map();
809
+ for (const thread of data.threads) {
810
+ for (const m of thread.history) {
811
+ if (seen.has(m.external_id) || m.role === "system" || !m.content) continue;
812
+ if (transcriptSegmentOf(m.tools)) continue;
813
+ seen.set(m.external_id, {
814
+ id: m.external_id,
815
+ senderExtId: m.role === "assistant" ? null : m.created_by_ext_id,
816
+ senderName: m.role === "assistant" ? "ARBI" : null,
817
+ text: m.content,
818
+ at: Date.parse(m.created_at)
819
+ });
820
+ }
821
+ }
822
+ return {
823
+ ref,
824
+ messages: [...seen.values()].sort((a, b) => a.at - b.at).slice(-HISTORY_LIMIT)
825
+ };
826
+ }
827
+ var SAME_MESSAGE_MS = 5 * 60 * 1e3;
828
+ function mergeChatLines(history, live, context) {
829
+ const historyLines = history.map((m) => ({
830
+ id: `h:${m.id}`,
831
+ senderIdentity: m.senderExtId ?? "arbi",
832
+ senderName: m.senderName ?? (m.senderExtId ? context.nameOf(m.senderExtId) : null) ?? "Someone",
833
+ text: m.text,
834
+ at: m.at,
835
+ mine: !!m.senderExtId && m.senderExtId === context.myIdentity,
836
+ status: "history"
837
+ }));
838
+ const used = /* @__PURE__ */ new Set();
839
+ const liveOnly = live.filter((line) => {
840
+ const match = history.findIndex(
841
+ (m, i) => !used.has(i) && m.senderExtId === line.senderIdentity && m.text === line.text && Math.abs(m.at - line.at) < SAME_MESSAGE_MS
842
+ );
843
+ if (match < 0) return true;
844
+ used.add(match);
845
+ return false;
846
+ });
847
+ return [...historyLines, ...liveOnly].sort((a, b) => a.at - b.at);
848
+ }
849
+ var CALL_RECORDING_TOPIC = "arbi.recording";
850
+ var RECORDING_CHUNK_MS = 3e4;
851
+ var SPEAKER_AUDIO_BITS_PER_SECOND = 24e3;
852
+ var COMPOSITE_VIDEO_BITS_PER_SECOND = 5e5;
853
+ var COMPOSITE_AUDIO_BITS_PER_SECOND = 32e3;
854
+ function partOffsetMs(partStartedAt, recordingStartedAt) {
855
+ const start = typeof recordingStartedAt === "number" ? recordingStartedAt : Date.parse(recordingStartedAt);
856
+ if (!Number.isFinite(start)) return 0;
857
+ return Math.max(0, Math.round(partStartedAt - start));
858
+ }
859
+ function newTrackKey() {
860
+ return client.generateChatKey();
861
+ }
862
+ async function wrapTrackKey(fileKey, conversationKey) {
863
+ await client.initSodium();
864
+ return client.bytesToBase64(client.encryptFile(fileKey, conversationKey));
865
+ }
866
+ async function unwrapTrackKey(wrapped, conversationKey) {
867
+ await client.initSodium();
868
+ return client.decryptFile(client.base64ToBytes(wrapped), conversationKey);
869
+ }
870
+ async function encryptPart(bytes, fileKey) {
871
+ await client.initSodium();
872
+ return client.encryptFile(bytes, fileKey);
873
+ }
874
+ async function decryptPart(cipher, fileKey) {
875
+ await client.initSodium();
876
+ return client.decryptFile(cipher, fileKey);
877
+ }
878
+ async function conversationKeyForCall(arbi, queryClient, call, options = {}) {
879
+ if (call.workspace_locked && call.locked_workspace_ext_id) {
880
+ const key2 = await arbi.workspaces.key(call.locked_workspace_ext_id);
881
+ return { key: key2, keyVersion: null };
882
+ }
883
+ let chatExtId = call.chat_ext_id ?? null;
884
+ if (!chatExtId) {
885
+ if (!options.callKey) throw new Error("This call has no meeting chat to keep a recording in");
886
+ const ref = await ensureMeetingChat(arbi, queryClient, call.external_id, options.callKey);
887
+ if (ref.kind !== "chat") throw new Error("Expected an end-to-end meeting chat");
888
+ chatExtId = ref.chatExtId;
889
+ }
890
+ const chat = await arbi.chats.ready(await chatByExtId(arbi, queryClient, chatExtId));
891
+ const ring = await arbi.chats.ring(chat);
892
+ const version = options.keyVersion ?? ring.currentVersion;
893
+ const key = ring.keys.get(version);
894
+ if (!key) throw new Error("No key for this recording in the meeting chat");
895
+ return { key, keyVersion: version };
896
+ }
897
+ async function meetingRefForCall(arbi, queryClient, call, callKey) {
898
+ const ref = meetingChatRefFrom(call);
899
+ if (ref) return ref;
900
+ if (!callKey) throw new Error("This call has no meeting chat yet");
901
+ return ensureMeetingChat(arbi, queryClient, call.external_id, callKey);
902
+ }
903
+ var defaultDeps = (arbi) => ({
904
+ createTrack: (...args) => arbi.calls.recording.createTrack(...args),
905
+ presign: (...args) => arbi.calls.recording.presignPart(...args),
906
+ commit: (...args) => arbi.calls.recording.commitPart(...args),
907
+ getRecording: (...args) => arbi.calls.recording.get(...args),
908
+ put: (url, body, headers) => browser.documents.presignedPut(url, body, void 0, headers),
909
+ encrypt: encryptPart,
910
+ wrap: wrapTrackKey,
911
+ unwrap: unwrapTrackKey,
912
+ newKey: newTrackKey,
913
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
914
+ });
915
+ var UPLOAD_ATTEMPTS = 5;
916
+ var UPLOAD_BACKOFF_MS = 1e3;
917
+ var SeqTakenError = class extends Error {
918
+ };
919
+ function isRetryable(err) {
920
+ if (!(err instanceof browser.CallApiError)) return true;
921
+ if (browser.calls.isQuotaError(err)) return false;
922
+ if (err.code === "part_not_uploaded") return true;
923
+ const s = err.status ?? 0;
924
+ return s === 0 || s === 408 || s === 429 || s >= 500 && s !== 507;
925
+ }
926
+ function isRecordingOver(err) {
927
+ if (!(err instanceof browser.CallApiError)) return false;
928
+ return err.code === "recording_stopped" || err.code === "composite_needs_video" || err.status === 404 || err.status === 410;
929
+ }
930
+ var TrackUploader = class {
931
+ constructor(options) {
932
+ this.options = options;
933
+ this.deps = { ...defaultDeps(options.arbi), ...options.deps };
934
+ }
935
+ options;
936
+ deps;
937
+ track = null;
938
+ trackPromise = null;
939
+ nextSeq = 0;
940
+ queue = [];
941
+ running = null;
942
+ /** No more parts are accepted (quota, or the recording is gone). */
943
+ stopped = false;
944
+ /** Parts committed (for tests and the UI). */
945
+ committed = 0;
946
+ /** Queue a part; parts upload one at a time, in order. */
947
+ enqueue(part) {
948
+ if (this.stopped) return;
949
+ this.queue.push(part);
950
+ this.drain();
951
+ }
952
+ /** Resolves once every queued part was uploaded (or given up). */
953
+ async flush() {
954
+ while (this.running) await this.running;
955
+ }
956
+ drain() {
957
+ if (this.running) return;
958
+ this.running = (async () => {
959
+ try {
960
+ while (this.queue.length && !this.stopped) {
961
+ const part = this.queue.shift();
962
+ await this.uploadPart(part);
963
+ }
964
+ } finally {
965
+ this.running = null;
966
+ }
967
+ })();
968
+ }
969
+ async withRetry(label, run) {
970
+ let lastError;
971
+ for (let attempt = 0; attempt < UPLOAD_ATTEMPTS; attempt++) {
972
+ try {
973
+ return await run();
974
+ } catch (err) {
975
+ lastError = err;
976
+ if (!isRetryable(err) || attempt === UPLOAD_ATTEMPTS - 1) break;
977
+ console.warn(`[calls] recording ${label} failed, retrying`, err);
978
+ await this.deps.sleep(UPLOAD_BACKOFF_MS * 2 ** attempt);
979
+ }
980
+ }
981
+ throw lastError;
982
+ }
983
+ ensureTrack() {
984
+ if (this.track) return Promise.resolve(this.track);
985
+ if (!this.trackPromise) {
986
+ this.trackPromise = this.withRetry("track", () => this.createTrack()).then(
987
+ (track) => {
988
+ this.track = track;
989
+ return track;
990
+ },
991
+ (err) => {
992
+ this.trackPromise = null;
993
+ throw err;
994
+ }
995
+ );
996
+ }
997
+ return this.trackPromise;
998
+ }
999
+ async createTrack() {
1000
+ const { callExtId, recordingExtId, kind, mimeType } = this.options;
1001
+ const conv = await this.options.conversationKey();
1002
+ const fileKey = await this.deps.newKey();
1003
+ const wrapped = await this.deps.wrap(fileKey, conv.key);
1004
+ const created = await this.deps.createTrack(callExtId, recordingExtId, {
1005
+ kind,
1006
+ wrapped_key: wrapped,
1007
+ key_version: conv.keyVersion,
1008
+ mime_type: mimeType,
1009
+ ...this.options.linkVersion ? { link_version: this.options.linkVersion } : {}
1010
+ });
1011
+ const key = created.wrapped_key && created.wrapped_key !== wrapped ? await this.deps.unwrap(created.wrapped_key, conv.key) : fileKey;
1012
+ let startedAt = this.options.recordingStartedAt ?? null;
1013
+ let parts = created.parts;
1014
+ if (!startedAt || !parts) {
1015
+ const recording = await this.deps.getRecording(callExtId, recordingExtId);
1016
+ startedAt = startedAt ?? recording.started_at;
1017
+ parts = parts ?? (recording.tracks ?? []).find((t) => t.external_id === created.external_id)?.parts;
1018
+ }
1019
+ this.nextSeq = Math.max(this.nextSeq, nextSeqAfter(parts ?? []));
1020
+ return { externalId: created.external_id, fileKey: key, startedAt };
1021
+ }
1022
+ async uploadPart(part) {
1023
+ const { callExtId, recordingExtId } = this.options;
1024
+ try {
1025
+ const track = await this.ensureTrack();
1026
+ const bytes = new Uint8Array(await part.blob.arrayBuffer());
1027
+ const cipher = await this.deps.encrypt(bytes, track.fileKey);
1028
+ const offset = partOffsetMs(part.startedAt, track.startedAt);
1029
+ let seq = this.nextSeq++;
1030
+ await this.withRetry("part", async () => {
1031
+ let upload;
1032
+ try {
1033
+ upload = await this.deps.presign(callExtId, recordingExtId, track.externalId, {
1034
+ seq,
1035
+ offset_ms: offset,
1036
+ duration_ms: Math.max(0, Math.round(part.durationMs)),
1037
+ size_bytes: cipher.length
1038
+ });
1039
+ } catch (err) {
1040
+ if (err instanceof browser.CallApiError && err.code === "part_committed") {
1041
+ seq = this.nextSeq++;
1042
+ throw new SeqTakenError(err.message);
1043
+ }
1044
+ throw err;
1045
+ }
1046
+ await this.deps.put(upload.upload_url, cipher, upload.headers ?? void 0);
1047
+ await this.deps.commit(callExtId, recordingExtId, track.externalId, seq);
1048
+ });
1049
+ this.committed += 1;
1050
+ } catch (err) {
1051
+ if (browser.calls.isQuotaError(err)) {
1052
+ this.stopped = true;
1053
+ this.queue = [];
1054
+ this.options.onStopped?.(err);
1055
+ return;
1056
+ }
1057
+ if (isRecordingOver(err)) {
1058
+ this.stopped = true;
1059
+ this.queue = [];
1060
+ }
1061
+ console.warn("[calls] a recording part could not be kept", err);
1062
+ this.options.onPartLost?.(err);
1063
+ }
1064
+ }
1065
+ };
1066
+ function nextSeqAfter(parts) {
1067
+ return parts.reduce((max, p) => Math.max(max, p.seq + 1), 0);
1068
+ }
1069
+ var uploaders = /* @__PURE__ */ new Map();
1070
+ function trackUploaderFor(options) {
1071
+ const key = `${options.recordingExtId}:${options.kind}`;
1072
+ let uploader = uploaders.get(key);
1073
+ if (!uploader || uploader.stopped) {
1074
+ uploader = new TrackUploader(options);
1075
+ uploaders.set(key, uploader);
1076
+ }
1077
+ return uploader;
1078
+ }
1079
+ function clearTrackUploaders() {
1080
+ uploaders.clear();
1081
+ }
1082
+
1083
+ // src/calls/recording-playback.ts
1084
+ var partKey = (p) => `${p.trackExtId}:${p.seq}`;
1085
+ function timelineOf(tracks) {
1086
+ return tracks.flatMap(
1087
+ (t) => (t.parts ?? []).map((p) => ({
1088
+ trackExtId: t.external_id,
1089
+ seq: p.seq,
1090
+ offsetMs: p.offset_ms,
1091
+ durationMs: p.duration_ms
1092
+ }))
1093
+ ).sort((a, b) => a.offsetMs - b.offsetMs || a.seq - b.seq);
1094
+ }
1095
+ function timelineDurationMs(parts) {
1096
+ return parts.reduce((max, p) => Math.max(max, p.offsetMs + p.durationMs), 0);
1097
+ }
1098
+ var PLAYBACK_LOOKAHEAD_MS = 2e4;
1099
+ function partsDue(parts, playheadMs, lookaheadMs, scheduled) {
1100
+ return parts.filter(
1101
+ (p) => !scheduled.has(partKey(p)) && p.offsetMs < playheadMs + lookaheadMs && p.offsetMs + p.durationMs > playheadMs
1102
+ );
1103
+ }
1104
+ function schedulePart(params) {
1105
+ const { partOffsetMs: partOffsetMs2, bufferDurationS, ctxStart, seekMs, ctxNow } = params;
1106
+ let when = ctxStart + (partOffsetMs2 - seekMs) / 1e3;
1107
+ let offset = 0;
1108
+ if (when < ctxNow) {
1109
+ offset = ctxNow - when;
1110
+ when = ctxNow;
1111
+ }
1112
+ if (offset >= bufferDurationS) return null;
1113
+ return { when, offset };
1114
+ }
1115
+ function playheadAt(ctxNow, ctxStart, seekMs) {
1116
+ return seekMs + Math.max(0, ctxNow - ctxStart) * 1e3;
1117
+ }
1118
+ var EBML_MAGIC = [26, 69, 223, 163];
1119
+ var FTYP = [102, 116, 121, 112];
1120
+ function startsMediaFile(bytes) {
1121
+ if (EBML_MAGIC.every((b, i) => bytes[i] === b)) return true;
1122
+ return FTYP.every((b, i) => bytes[4 + i] === b);
1123
+ }
1124
+ function splitIntoFiles(parts) {
1125
+ const files = [];
1126
+ for (const part of parts) {
1127
+ if (!files.length || startsMediaFile(part)) files.push([part]);
1128
+ else files[files.length - 1].push(part);
1129
+ }
1130
+ return files;
1131
+ }
1132
+ function extensionFor(mimeType) {
1133
+ if (mimeType.includes("mp4")) return mimeType.startsWith("video") ? "mp4" : "m4a";
1134
+ if (mimeType.includes("ogg")) return "ogg";
1135
+ return "webm";
1136
+ }
1137
+ function fileSafe(name) {
1138
+ return name.replace(/[^\p{L}\p{N} ._-]+/gu, "").trim().replace(/\s+/g, "-").slice(0, 60) || "recording";
1139
+ }
1140
+ var EXPORT_SAMPLE_RATE = 16e3;
1141
+ function writeSamples(target, samples, offsetSamples) {
1142
+ const start = Math.max(0, Math.round(offsetSamples));
1143
+ const n = Math.min(samples.length, target.length - start);
1144
+ for (let i = 0; i < n; i++) {
1145
+ const s = Math.max(-1, Math.min(1, samples[i]));
1146
+ target[start + i] = s < 0 ? s * 32768 : s * 32767;
1147
+ }
1148
+ }
1149
+ function encodeWav(samples, sampleRate) {
1150
+ const dataBytes = samples.length * 2;
1151
+ const out = new Uint8Array(44 + dataBytes);
1152
+ const view = new DataView(out.buffer);
1153
+ const ascii = (offset, text) => {
1154
+ for (let i = 0; i < text.length; i++) out[offset + i] = text.charCodeAt(i);
1155
+ };
1156
+ ascii(0, "RIFF");
1157
+ view.setUint32(4, 36 + dataBytes, true);
1158
+ ascii(8, "WAVE");
1159
+ ascii(12, "fmt ");
1160
+ view.setUint32(16, 16, true);
1161
+ view.setUint16(20, 1, true);
1162
+ view.setUint16(22, 1, true);
1163
+ view.setUint32(24, sampleRate, true);
1164
+ view.setUint32(28, sampleRate * 2, true);
1165
+ view.setUint16(32, 2, true);
1166
+ view.setUint16(34, 16, true);
1167
+ ascii(36, "data");
1168
+ view.setUint32(40, dataBytes, true);
1169
+ for (let i = 0; i < samples.length; i++) view.setInt16(44 + i * 2, samples[i], true);
1170
+ return out;
1171
+ }
1172
+ function standalone(bytes) {
1173
+ return new Uint8Array(bytes);
1174
+ }
1175
+ function floatToWav(samples, sampleRate) {
1176
+ const pcm = new Int16Array(samples.length);
1177
+ writeSamples(pcm, samples, 0);
1178
+ return encodeWav(pcm, sampleRate);
1179
+ }
1180
+ var SEGMENT_FRAME_MS = 50;
1181
+ var SEGMENT_PRE_ROLL_MS = 200;
1182
+ var RECORDING_SEGMENTER = {
1183
+ maxMs: 25e3,
1184
+ minVoiceMs: 300,
1185
+ silenceMs: 1500
1186
+ };
1187
+ var SHORT_PIECE_MERGE_GAP_MS = 1e3;
1188
+ function createTrackCutter(sampleRate, config = {}, options = {}) {
1189
+ const cfg = { ...chunkEEIYXVM4_cjs.DEFAULT_SEGMENTER_CONFIG, ...config };
1190
+ const frame = Math.max(1, Math.round(sampleRate * SEGMENT_FRAME_MS / 1e3));
1191
+ const preRoll = Math.round(SEGMENT_PRE_ROLL_MS / 1e3 * sampleRate);
1192
+ const toSample = (ms) => Math.round(ms / 1e3 * sampleRate);
1193
+ const toMs = (sample) => sample / sampleRate * 1e3;
1194
+ let buf = new Float32Array(sampleRate * 4);
1195
+ let bufStart = 0;
1196
+ let len = 0;
1197
+ let origin = null;
1198
+ let cursor = 0;
1199
+ let nextFrame = 0;
1200
+ let state2 = chunkEEIYXVM4_cjs.INITIAL_SEGMENTER_STATE;
1201
+ let pending2 = null;
1202
+ let out = [];
1203
+ const append = (samples) => {
1204
+ if (len + samples.length > buf.length) {
1205
+ const grown = new Float32Array(Math.max(buf.length * 2, len + samples.length));
1206
+ grown.set(buf.subarray(0, len));
1207
+ buf = grown;
1208
+ }
1209
+ buf.set(samples, len);
1210
+ len += samples.length;
1211
+ cursor += samples.length;
1212
+ };
1213
+ const emit = (piece) => {
1214
+ const from = Math.max(piece.start, bufStart);
1215
+ if (piece.end <= from) return;
1216
+ out.push({
1217
+ start: from,
1218
+ end: piece.end,
1219
+ voiceMs: piece.voiceMs,
1220
+ samples: buf.slice(from - bufStart, piece.end - bufStart)
1221
+ });
1222
+ };
1223
+ const onEvents = (events) => {
1224
+ for (const e of events) {
1225
+ if (e.type === "start") {
1226
+ if (pending2 && e.at - pending2.at > SHORT_PIECE_MERGE_GAP_MS) pending2 = null;
1227
+ continue;
1228
+ }
1229
+ let piece = {
1230
+ start: Math.max(origin ?? 0, toSample(e.startedAt) - preRoll),
1231
+ end: Math.min(cursor, toSample(e.at)),
1232
+ voiceMs: e.voiceMs,
1233
+ at: e.at
1234
+ };
1235
+ if (pending2) {
1236
+ if (piece.end - pending2.start <= toSample(cfg.maxMs) + preRoll) {
1237
+ piece = { ...piece, start: pending2.start, voiceMs: piece.voiceMs + pending2.voiceMs };
1238
+ }
1239
+ pending2 = null;
1240
+ }
1241
+ if (piece.voiceMs >= cfg.minVoiceMs) emit(piece);
1242
+ else if (options.mergeShort && piece.end > piece.start) pending2 = piece;
1243
+ }
1244
+ };
1245
+ const step = (from, n) => {
1246
+ let sum = 0;
1247
+ const base = from - bufStart;
1248
+ for (let j = 0; j < n; j++) sum += buf[base + j] * buf[base + j];
1249
+ const result = chunkEEIYXVM4_cjs.stepSegmenter(state2, chunkEEIYXVM4_cjs.levelFromRms(Math.sqrt(sum / n)), toMs(from), cfg);
1250
+ state2 = result.state;
1251
+ onEvents(result.events);
1252
+ };
1253
+ const run = () => {
1254
+ while (nextFrame + frame <= cursor) {
1255
+ step(nextFrame, frame);
1256
+ nextFrame += frame;
1257
+ }
1258
+ let keepFrom = cursor - preRoll;
1259
+ if (state2.phase === "voice") keepFrom = Math.min(keepFrom, toSample(state2.startedAt) - preRoll);
1260
+ if (pending2) keepFrom = Math.min(keepFrom, pending2.start);
1261
+ keepFrom = Math.min(Math.max(keepFrom, bufStart), nextFrame);
1262
+ if (keepFrom > bufStart) {
1263
+ buf.copyWithin(0, keepFrom - bufStart, len);
1264
+ len -= keepFrom - bufStart;
1265
+ bufStart = keepFrom;
1266
+ }
1267
+ };
1268
+ const take = () => {
1269
+ const done = out;
1270
+ out = [];
1271
+ return done;
1272
+ };
1273
+ return {
1274
+ push(offsetMs, samples) {
1275
+ const at = toSample(Math.max(0, offsetMs));
1276
+ if (origin === null) {
1277
+ origin = at;
1278
+ bufStart = cursor = nextFrame = at;
1279
+ }
1280
+ if (at > cursor) {
1281
+ const second = new Float32Array(sampleRate);
1282
+ while (cursor < at) {
1283
+ append(second.subarray(0, Math.min(sampleRate, at - cursor)));
1284
+ run();
1285
+ }
1286
+ }
1287
+ const fresh = at < cursor ? samples.subarray(Math.min(samples.length, cursor - at)) : samples;
1288
+ if (fresh.length) {
1289
+ append(fresh);
1290
+ run();
1291
+ }
1292
+ return take();
1293
+ },
1294
+ finish() {
1295
+ if (origin !== null) {
1296
+ if (nextFrame < cursor) {
1297
+ step(nextFrame, cursor - nextFrame);
1298
+ nextFrame = cursor;
1299
+ }
1300
+ onEvents(chunkEEIYXVM4_cjs.flushSegmenter(state2, toMs(cursor), cfg).events);
1301
+ state2 = chunkEEIYXVM4_cjs.INITIAL_SEGMENTER_STATE;
1302
+ }
1303
+ pending2 = null;
1304
+ return take();
1305
+ }
1306
+ };
1307
+ }
1308
+ function cutAtPauses(samples, sampleRate, config = {}) {
1309
+ const cutter = createTrackCutter(sampleRate, config);
1310
+ return [...cutter.push(0, samples), ...cutter.finish()].map(({ start, end }) => ({ start, end }));
1311
+ }
1312
+ var CALL_CAPTION_TOPIC = "arbi.caption";
1313
+ var CALL_TRANSCRIPTION_TOPIC = "arbi.transcription";
1314
+ var CAPTION_MAX_CHARS = 2e3;
1315
+ var LIVE_SEGMENTER = { minVoiceMs: 400, holdShortMs: 1e3 };
1316
+ var encoder2 = new TextEncoder();
1317
+ var decoder2 = new TextDecoder();
1318
+ var SEGMENT_ID_PATTERN = /^[A-Za-z0-9_-]{8,64}$/;
1319
+ function newSegmentId() {
1320
+ const bytes = new Uint8Array(12);
1321
+ globalThis.crypto.getRandomValues(bytes);
1322
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1323
+ }
1324
+ async function encodeCaptionPacket(packet, callKey) {
1325
+ return encoder2.encode(await client.encryptWithChatKey(JSON.stringify(packet), callKey));
1326
+ }
1327
+ async function decodeCaptionPacket(payload, callKey) {
1328
+ try {
1329
+ const parsed = JSON.parse(await client.decryptWithChatKey(decoder2.decode(payload), callKey));
1330
+ if (!parsed || typeof parsed !== "object") return null;
1331
+ const p = parsed;
1332
+ if (p.v !== 1 || typeof p.segment_id !== "string" || !SEGMENT_ID_PATTERN.test(p.segment_id) || typeof p.text !== "string" || typeof p.identity !== "string") {
1333
+ return null;
1334
+ }
1335
+ const text = p.text.trim().slice(0, CAPTION_MAX_CHARS);
1336
+ if (!text) return null;
1337
+ return {
1338
+ v: 1,
1339
+ segment_id: p.segment_id,
1340
+ text,
1341
+ identity: p.identity,
1342
+ name: typeof p.name === "string" ? p.name : p.identity,
1343
+ t: typeof p.t === "number" ? p.t : Date.now(),
1344
+ ...p.proxy === true ? { proxy: true } : {}
1345
+ };
1346
+ } catch {
1347
+ return null;
1348
+ }
1349
+ }
1350
+ function transcriptPersistRole(params) {
1351
+ if (!params.canPost || !params.hasCallKey) return null;
1352
+ if (params.speakerIdentity === params.myIdentity) return "own";
1353
+ if (params.speakerNeedsProxy) return "proxy";
1354
+ return null;
1355
+ }
1356
+ function threadTranscriptText(segment) {
1357
+ return `${segment.speakerName}: ${segment.text}`;
1358
+ }
1359
+ async function persistTranscriptSegment(arbi, queryClient, callExtId, callKey, segment) {
1360
+ const ref = await ensureMeetingChat(arbi, queryClient, callExtId, callKey);
1361
+ await storeTranscriptSegment(arbi, queryClient, ref, segment);
1362
+ return ref;
1363
+ }
1364
+ async function storeTranscriptSegment(arbi, queryClient, ref, segment) {
1365
+ if (ref.kind === "chat") {
1366
+ const chat = await arbi.chats.ready(await chatByExtId(arbi, queryClient, ref.chatExtId));
1367
+ const ring = await arbi.chats.ring(chat);
1368
+ const key = ring.keys.get(ring.currentVersion);
1369
+ if (!key) throw new Error("No key for the meeting chat");
1370
+ const content = {
1371
+ text: segment.text,
1372
+ speaker_identity: segment.speakerIdentity,
1373
+ speaker_name: segment.speakerName,
1374
+ started_at: segment.startedAt
1375
+ };
1376
+ await arbi.calls.transcription.postChatLine(ref.chatExtId, {
1377
+ content: await client.encryptWithChatKey(JSON.stringify(content), key),
1378
+ key_version: ring.currentVersion,
1379
+ dedupe_key: segment.segmentId
1380
+ });
1381
+ return;
1382
+ }
1383
+ const transcript = {
1384
+ segment_id: segment.segmentId,
1385
+ speaker_ext_id: segment.speakerIdentity,
1386
+ started_at: segment.startedAt
1387
+ };
1388
+ await arbi.conversations.postMessage({
1389
+ content: threadTranscriptText(segment),
1390
+ conversation_ext_id: ref.conversationExtId,
1391
+ assistant_mode: "mentioned",
1392
+ transcript
1393
+ });
1394
+ }
1395
+ async function openRecording(arbi, queryClient, call, recordingExtId, loaded) {
1396
+ const recording = loaded ?? await arbi.calls.recording.get(call.external_id, recordingExtId);
1397
+ const convKeys = /* @__PURE__ */ new Map();
1398
+ const keys = /* @__PURE__ */ new Map();
1399
+ for (const track of recording.tracks ?? []) {
1400
+ const version = track.key_version ?? null;
1401
+ const id = String(version);
1402
+ if (!convKeys.has(id)) {
1403
+ convKeys.set(
1404
+ id,
1405
+ conversationKeyForCall(arbi, queryClient, call, { keyVersion: version }).then((c) => c.key)
1406
+ );
1407
+ }
1408
+ try {
1409
+ keys.set(track.external_id, await unwrapTrackKey(track.wrapped_key, await convKeys.get(id)));
1410
+ } catch (err) {
1411
+ console.warn("[calls] a recording track key does not open", err);
1412
+ }
1413
+ }
1414
+ return { recording, keys };
1415
+ }
1416
+ function speakerTracks(recording) {
1417
+ return (recording.tracks ?? []).filter((t) => t.kind === "speaker");
1418
+ }
1419
+ function compositeTrack(recording) {
1420
+ return (recording.tracks ?? []).find((t) => t.kind === "composite") ?? null;
1421
+ }
1422
+ function sortedParts(track) {
1423
+ return [...track.parts ?? []].sort((a, b) => a.seq - b.seq);
1424
+ }
1425
+ async function fetchPart(arbi, part, fileKey) {
1426
+ if (!part.download_url) throw new Error("This recording\u2019s media was deleted");
1427
+ return decryptPart(await arbi.calls.recording.downloadPart(part.download_url), fileKey);
1428
+ }
1429
+ async function compositeFiles(arbi, track, fileKey) {
1430
+ const parts = [];
1431
+ for (const part of sortedParts(track)) parts.push(await fetchPart(arbi, part, fileKey));
1432
+ const type = track.mime_type.split(";")[0] || "video/webm";
1433
+ return splitIntoFiles(parts).map((file) => new Blob(file.map(standalone), { type }));
1434
+ }
1435
+ async function decodeMono16k(bytes) {
1436
+ const ctx = new OfflineAudioContext(1, 1, EXPORT_SAMPLE_RATE);
1437
+ const buffer = await ctx.decodeAudioData(standalone(bytes).buffer);
1438
+ return buffer.getChannelData(0);
1439
+ }
1440
+ async function speakerWav(arbi, track, fileKey, onPart) {
1441
+ const parts = sortedParts(track);
1442
+ const totalMs = timelineDurationMs(timelineOf([track]));
1443
+ const samples = new Int16Array(Math.ceil(totalMs / 1e3 * EXPORT_SAMPLE_RATE) + 1);
1444
+ for (const part of parts) {
1445
+ const bytes = await fetchPart(arbi, part, fileKey);
1446
+ try {
1447
+ writeSamples(
1448
+ samples,
1449
+ await decodeMono16k(bytes),
1450
+ part.offset_ms / 1e3 * EXPORT_SAMPLE_RATE
1451
+ );
1452
+ } catch (err) {
1453
+ console.warn("[calls] a recording part does not decode", err);
1454
+ }
1455
+ onPart?.();
1456
+ }
1457
+ return new Blob([encodeWav(samples, EXPORT_SAMPLE_RATE)], { type: "audio/wav" });
1458
+ }
1459
+ async function recordingFiles(arbi, opened, title, onProgress) {
1460
+ const { recording, keys } = opened;
1461
+ const base = fileSafe(title || "Meeting");
1462
+ const date = recording.started_at.slice(0, 10);
1463
+ const total = (recording.tracks ?? []).reduce((n, t) => n + (t.parts?.length ?? 0), 0);
1464
+ let done = 0;
1465
+ const tick = () => onProgress?.(++done, total);
1466
+ const files = [];
1467
+ for (const track of speakerTracks(recording)) {
1468
+ const key = keys.get(track.external_id);
1469
+ if (!key || !track.parts?.length) continue;
1470
+ const wav = await speakerWav(arbi, track, key, tick);
1471
+ const who = fileSafe(track.speaker_name || track.speaker_ext_id || "speaker");
1472
+ files.push(new File([wav], `${base}-${date}-${who}.wav`, { type: "audio/wav" }));
1473
+ }
1474
+ const composite = compositeTrack(recording);
1475
+ const compositeKey = composite && keys.get(composite.external_id);
1476
+ if (composite && compositeKey && composite.parts?.length) {
1477
+ const videos = await compositeFiles(arbi, composite, compositeKey);
1478
+ done += composite.parts.length;
1479
+ onProgress?.(done, total);
1480
+ const ext = extensionFor(composite.mime_type);
1481
+ videos.forEach(
1482
+ (blob, i) => files.push(
1483
+ new File([blob], `${base}-${date}-video${videos.length > 1 ? `-${i + 1}` : ""}.${ext}`, {
1484
+ type: blob.type
1485
+ })
1486
+ )
1487
+ );
1488
+ }
1489
+ return files;
1490
+ }
1491
+ var PROMPT_HISTORY_CHARS = 400;
1492
+ async function transcribeRecording(params) {
1493
+ const {
1494
+ arbi,
1495
+ queryClient,
1496
+ callExtId,
1497
+ opened,
1498
+ ref,
1499
+ onProgress,
1500
+ decode = decodeMono16k,
1501
+ language
1502
+ } = params;
1503
+ const { recording, keys } = opened;
1504
+ const tracks = speakerTracks(recording).filter((t) => keys.has(t.external_id));
1505
+ const total = tracks.reduce((n, t) => n + (t.parts?.length ?? 0), 0);
1506
+ const start = Date.parse(recording.started_at);
1507
+ let done = 0;
1508
+ let stored = 0;
1509
+ let failed = 0;
1510
+ for (const track of tracks) {
1511
+ const key = keys.get(track.external_id);
1512
+ const cutter = createTrackCutter(EXPORT_SAMPLE_RATE, RECORDING_SEGMENTER, { mergeShort: true });
1513
+ let previous = "";
1514
+ let nextSegment = 0;
1515
+ const send = async (request) => {
1516
+ try {
1517
+ const result = await arbi.calls.recording.transcribe(callExtId, recording.external_id, {
1518
+ audio: request.audio,
1519
+ trackExtId: track.external_id,
1520
+ seq: request.seq ?? null,
1521
+ segment: request.segment ?? null,
1522
+ segmentOffsetMs: request.seq == null ? request.offsetMs : 0,
1523
+ language,
1524
+ prompt: browser.continuityPrompt(previous)
1525
+ });
1526
+ const text = result.text.trim();
1527
+ if (!text) return;
1528
+ previous = `${previous} ${text}`.slice(-PROMPT_HISTORY_CHARS);
1529
+ const segment = {
1530
+ segmentId: result.segment_id || (request.seq != null ? `rec-${track.external_id}-${request.seq}` : `rec-${track.external_id}-s${request.segment}`),
1531
+ text,
1532
+ speakerIdentity: result.speaker_ext_id ?? track.speaker_ext_id ?? "",
1533
+ speakerName: result.speaker_name ?? track.speaker_name ?? "Speaker",
1534
+ startedAt: Number.isFinite(start) ? new Date(start + (result.offset_ms ?? Math.round(request.offsetMs))).toISOString() : null
1535
+ };
1536
+ await storeTranscriptSegment(arbi, queryClient, ref, segment);
1537
+ stored += 1;
1538
+ } catch (err) {
1539
+ failed += 1;
1540
+ console.warn("[calls] a recording piece could not be transcribed", err);
1541
+ }
1542
+ };
1543
+ const sendPieces = async (pieces) => {
1544
+ for (const piece of pieces) {
1545
+ await send({
1546
+ audio: new Blob([floatToWav(piece.samples, EXPORT_SAMPLE_RATE)], { type: "audio/wav" }),
1547
+ segment: nextSegment++,
1548
+ offsetMs: piece.start / EXPORT_SAMPLE_RATE * 1e3
1549
+ });
1550
+ }
1551
+ };
1552
+ for (const part of sortedParts(track)) {
1553
+ let bytes;
1554
+ try {
1555
+ bytes = await fetchPart(arbi, part, key);
1556
+ } catch (err) {
1557
+ failed += 1;
1558
+ console.warn("[calls] a recording part could not be read", err);
1559
+ onProgress?.(++done, total);
1560
+ continue;
1561
+ }
1562
+ let pcm = null;
1563
+ try {
1564
+ pcm = await decode(bytes);
1565
+ } catch (err) {
1566
+ console.warn("[calls] a recording part does not decode; sending it whole", err);
1567
+ }
1568
+ if (pcm) {
1569
+ await sendPieces(cutter.push(part.offset_ms, pcm));
1570
+ } else {
1571
+ await send({
1572
+ audio: new Blob([standalone(bytes)], { type: track.mime_type }),
1573
+ seq: part.seq,
1574
+ offsetMs: part.offset_ms
1575
+ });
1576
+ }
1577
+ onProgress?.(++done, total);
1578
+ }
1579
+ await sendPieces(cutter.finish());
1580
+ }
1581
+ return { stored, failed };
1582
+ }
1583
+ function useCallsConfig() {
1584
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1585
+ const { data } = reactQuery.useQuery({
1586
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.config(),
1587
+ queryFn: () => arbi.calls.config(),
1588
+ enabled: arbi.isLoggedIn,
1589
+ staleTime: 5 * 6e4,
1590
+ retry: false
1591
+ });
1592
+ return data;
1593
+ }
1594
+ function useServerCallsEnabled() {
1595
+ return useCallsConfig()?.enabled === true;
1596
+ }
1597
+ function useCallTranscriptionAvailable() {
1598
+ return useCallsConfig()?.transcription_available === true;
1599
+ }
1600
+ function useCall(callExtId) {
1601
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1602
+ return reactQuery.useQuery({
1603
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.call(callExtId ?? ""),
1604
+ queryFn: () => arbi.calls.get(callExtId),
1605
+ enabled: !!callExtId && arbi.isLoggedIn,
1606
+ staleTime: 6e4,
1607
+ retry: false
1608
+ });
1609
+ }
1610
+ function useCallRecordings(callExtId, enabled = true) {
1611
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1612
+ return reactQuery.useQuery({
1613
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recordings(callExtId ?? ""),
1614
+ queryFn: () => arbi.calls.recording.list(callExtId),
1615
+ enabled: !!callExtId && enabled && arbi.isLoggedIn,
1616
+ retry: false
1617
+ });
1618
+ }
1619
+ function useCallRecording(callExtId, recordingExtId) {
1620
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1621
+ return reactQuery.useQuery({
1622
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recording(callExtId ?? "", recordingExtId ?? ""),
1623
+ queryFn: () => arbi.calls.recording.get(callExtId, recordingExtId),
1624
+ enabled: !!callExtId && !!recordingExtId && arbi.isLoggedIn,
1625
+ retry: false
1626
+ });
1627
+ }
1628
+ var NO_WINDOWS = [];
1629
+ function useRecordingWindows(callExtId, enabled) {
1630
+ const { data } = useCallRecordings(callExtId, enabled);
1631
+ return react.useMemo(() => data ? recordingWindowsOf(data) : NO_WINDOWS, [data]);
1632
+ }
1633
+ function useCallInviteLinks(callExtId) {
1634
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1635
+ return reactQuery.useQuery({
1636
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.inviteLinks(callExtId ?? ""),
1637
+ queryFn: () => arbi.calls.inviteLinks.list(callExtId),
1638
+ enabled: !!callExtId && arbi.isLoggedIn,
1639
+ retry: false
1640
+ });
1641
+ }
1642
+ function useRecordingActions(call) {
1643
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1644
+ const queryClient = reactQuery.useQueryClient();
1645
+ return react.useMemo(
1646
+ () => ({
1647
+ refresh: () => void queryClient.invalidateQueries({
1648
+ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recordingsOf(call.external_id)
1649
+ }),
1650
+ open: (recording) => openRecording(arbi, queryClient, call, recording.external_id, recording),
1651
+ transcribe: async (opened, onProgress) => transcribeRecording({
1652
+ arbi,
1653
+ queryClient,
1654
+ callExtId: call.external_id,
1655
+ opened,
1656
+ ref: await meetingRefForCall(arbi, queryClient, call),
1657
+ onProgress
1658
+ })
1659
+ }),
1660
+ [arbi, queryClient, call]
1661
+ );
1662
+ }
1663
+ function useRevokeCallInviteLink(callExtId) {
1664
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1665
+ const queryClient = reactQuery.useQueryClient();
1666
+ return react.useCallback(
1667
+ async (inviteExtId) => {
1668
+ await arbi.calls.inviteLinks.revoke(callExtId, inviteExtId);
1669
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.callQueryKeys.inviteLinks(callExtId) });
1670
+ },
1671
+ [arbi, queryClient, callExtId]
1672
+ );
1673
+ }
1674
+ var DEFAULT_JOIN_CHOICES = { audioEnabled: true, videoEnabled: false };
1675
+ var EMPTY_CALL_SESSION = {
1676
+ active: null,
1677
+ incoming: [],
1678
+ knocks: [],
1679
+ liveCalls: {}
1680
+ };
1681
+ var state = EMPTY_CALL_SESSION;
1682
+ var listeners = /* @__PURE__ */ new Set();
1683
+ function update(next) {
1684
+ const changed = next(state);
1685
+ if (changed === state) return;
1686
+ state = changed;
1687
+ for (const listener of listeners) listener();
1688
+ }
1689
+ var callSession = {
1690
+ getState: () => state,
1691
+ subscribe(listener) {
1692
+ listeners.add(listener);
1693
+ return () => {
1694
+ listeners.delete(listener);
1695
+ };
1696
+ },
1697
+ setActiveCall(next) {
1698
+ update((s) => ({
1699
+ ...s,
1700
+ active: { ...next, minimized: next.minimized ?? false, startedAt: Date.now() },
1701
+ // Joining a call answers any ring for it; knocks belong to the previous call.
1702
+ incoming: s.incoming.filter((ring) => ring.call_ext_id !== next.callExtId),
1703
+ knocks: s.knocks.filter((k) => k.callExtId === next.callExtId)
1704
+ }));
1705
+ },
1706
+ /** Patch the active call (no-op when it is a different call or none). */
1707
+ updateActiveCall(callExtId, patch) {
1708
+ update(
1709
+ (s) => s.active?.callExtId === callExtId ? { ...s, active: { ...s.active, ...patch } } : s
1710
+ );
1711
+ },
1712
+ endActiveCall() {
1713
+ update((s) => {
1714
+ s.active?.knock?.abort();
1715
+ return { ...s, active: null, knocks: [] };
1716
+ });
1717
+ },
1718
+ setCallMinimized(minimized) {
1719
+ update((s) => s.active ? { ...s, active: { ...s.active, minimized } } : s);
1720
+ },
1721
+ /** Queue a ring. A repeat ring for the same call replaces the earlier entry. */
1722
+ enqueueIncomingCall(ring) {
1723
+ update((s) => {
1724
+ if (s.active?.callExtId === ring.call_ext_id) return s;
1725
+ return {
1726
+ ...s,
1727
+ incoming: [
1728
+ ...s.incoming.filter((r) => r.call_ext_id !== ring.call_ext_id),
1729
+ { ...ring, receivedAt: Date.now() }
1730
+ ]
1731
+ };
1732
+ });
1733
+ },
1734
+ removeIncomingCall(callExtId) {
1735
+ update((s) => ({ ...s, incoming: s.incoming.filter((r) => r.call_ext_id !== callExtId) }));
1736
+ },
1737
+ addKnock(knock) {
1738
+ update((s) => {
1739
+ if (s.active?.callExtId !== knock.callExtId) return s;
1740
+ return {
1741
+ ...s,
1742
+ knocks: [
1743
+ ...s.knocks.filter((k) => k.knockId !== knock.knockId),
1744
+ { ...knock, receivedAt: Date.now() }
1745
+ ]
1746
+ };
1747
+ });
1748
+ },
1749
+ removeKnock(knockId) {
1750
+ update((s) => ({ ...s, knocks: s.knocks.filter((k) => k.knockId !== knockId) }));
1751
+ },
1752
+ markCallLive(callExtId, where) {
1753
+ update((s) => ({ ...s, liveCalls: { ...s.liveCalls, [callExtId]: where } }));
1754
+ },
1755
+ /** Call ended: forget it and drop any unanswered ring / knock for it. */
1756
+ markCallEnded(callExtId) {
1757
+ update((s) => {
1758
+ const liveCalls = { ...s.liveCalls };
1759
+ delete liveCalls[callExtId];
1760
+ return {
1761
+ ...s,
1762
+ liveCalls,
1763
+ incoming: s.incoming.filter((r) => r.call_ext_id !== callExtId),
1764
+ knocks: s.knocks.filter((k) => k.callExtId !== callExtId)
1765
+ };
1766
+ });
1767
+ }
1768
+ };
1769
+ function resetCallSession() {
1770
+ update(() => EMPTY_CALL_SESSION);
1771
+ }
1772
+ function useCallSession(selector) {
1773
+ return react.useSyncExternalStore(
1774
+ callSession.subscribe,
1775
+ () => selector(state),
1776
+ () => selector(state)
1777
+ );
1778
+ }
1779
+ function threadLiveCallId(s, conversationExtId) {
1780
+ const found = Object.entries(s.liveCalls).find(
1781
+ ([, c]) => c.logConversationExtId === conversationExtId
1782
+ );
1783
+ return found ? found[0] : null;
1784
+ }
1785
+ function threadHasLiveCall(s, conversationExtId) {
1786
+ return threadLiveCallId(s, conversationExtId) !== null;
1787
+ }
1788
+ function chatLiveCallId(s, chatExtId) {
1789
+ const found = Object.entries(s.liveCalls).find(([, c]) => c.chatExtId === chatExtId);
1790
+ return found ? found[0] : null;
1791
+ }
1792
+ function chatHasLiveCall(s, chatExtId) {
1793
+ return chatLiveCallId(s, chatExtId) !== null;
1794
+ }
1795
+
1796
+ // src/calls/moderation.ts
1797
+ var CALL_MODERATION_TOPIC = "arbi.moderation";
1798
+ function trackOf(value) {
1799
+ return value === "audio" || value === "video" ? value : null;
1800
+ }
1801
+ function mutedNoticeFromPacket(payload) {
1802
+ try {
1803
+ const parsed = JSON.parse(new TextDecoder().decode(payload));
1804
+ if (!parsed || typeof parsed !== "object") return null;
1805
+ const p = parsed;
1806
+ const track = trackOf(p.track);
1807
+ if (p.action !== "muted" || !track) return null;
1808
+ return { track, byName: typeof p.by_name === "string" ? p.by_name : null };
1809
+ } catch {
1810
+ return null;
1811
+ }
1812
+ }
1813
+ function mutedNoticeText(notice) {
1814
+ return notice.track === "audio" ? "The host muted you" : "The host turned off your camera";
1815
+ }
1816
+ var MUTED_DEDUPE_MS = 5e3;
1817
+ function createMutedNotifier(show, now = Date.now) {
1818
+ const last = /* @__PURE__ */ new Map();
1819
+ return (notice) => {
1820
+ const at = now();
1821
+ const prev = last.get(notice.track);
1822
+ if (prev !== void 0 && at - prev < MUTED_DEDUPE_MS) return;
1823
+ last.set(notice.track, at);
1824
+ show(mutedNoticeText(notice));
1825
+ };
1826
+ }
1827
+ function mutedNoticeFromEvent(raw) {
1828
+ if (!raw || typeof raw !== "object") return null;
1829
+ const r = raw;
1830
+ const track = trackOf(r.track);
1831
+ if (typeof r.call_ext_id !== "string" || !track) return null;
1832
+ return {
1833
+ callExtId: r.call_ext_id,
1834
+ track,
1835
+ byName: typeof r.by_name === "string" ? r.by_name : null
1836
+ };
1837
+ }
1838
+ var listeners2 = /* @__PURE__ */ new Map();
1839
+ function onCallEvent(type, listener) {
1840
+ let set = listeners2.get(type);
1841
+ if (!set) listeners2.set(type, set = /* @__PURE__ */ new Set());
1842
+ set.add(listener);
1843
+ return () => {
1844
+ set.delete(listener);
1845
+ };
1846
+ }
1847
+ function relay(type, message) {
1848
+ if (!message) return;
1849
+ for (const listener of listeners2.get(type) ?? []) {
1850
+ listener(message);
1851
+ }
1852
+ }
1853
+ var str = (value) => typeof value === "string" && value ? value : null;
1854
+ function applyCallEvent(queryClient, event, options = {}) {
1855
+ const m = event;
1856
+ const callExtId = str(m.call_ext_id);
1857
+ switch (m.type) {
1858
+ case "call.ringing": {
1859
+ const ring = m;
1860
+ if (options.acceptRings === false || !callExtId || !ring.sealed_key) return true;
1861
+ if (options.me && ring.caller_ext_id === options.me) return true;
1862
+ callSession.enqueueIncomingCall({
1863
+ call_ext_id: ring.call_ext_id,
1864
+ room_name: ring.room_name,
1865
+ caller_ext_id: ring.caller_ext_id,
1866
+ caller_name: ring.caller_name,
1867
+ chat_ext_id: ring.chat_ext_id ?? null,
1868
+ log_conversation_ext_id: ring.log_conversation_ext_id ?? null,
1869
+ meeting_conversation_ext_id: ring.meeting_conversation_ext_id ?? null,
1870
+ workspace_ext_id: ring.workspace_ext_id ?? null,
1871
+ context: ring.context ?? null,
1872
+ sealed_key: ring.sealed_key,
1873
+ link_version: ring.link_version,
1874
+ title: ring.title ?? null
1875
+ });
1876
+ return true;
1877
+ }
1878
+ case "call.declined":
1879
+ if (callExtId && callSession.getState().active?.callExtId === callExtId) {
1880
+ chunkVAMPYLQ4_cjs.notify.info("Call declined", { record: false, ambient: false });
1881
+ }
1882
+ return true;
1883
+ case "call.started":
1884
+ if (!callExtId) return true;
1885
+ callSession.markCallLive(callExtId, {
1886
+ chatExtId: str(m.chat_ext_id),
1887
+ logConversationExtId: str(m.log_conversation_ext_id),
1888
+ meetingConversationExtId: str(m.meeting_conversation_ext_id)
1889
+ });
1890
+ invalidateCall(queryClient, {
1891
+ call_ext_id: callExtId,
1892
+ log_conversation_ext_id: str(m.log_conversation_ext_id)
1893
+ });
1894
+ return true;
1895
+ case "call.ended":
1896
+ if (!callExtId) return true;
1897
+ callSession.markCallEnded(callExtId);
1898
+ invalidateCall(queryClient, {
1899
+ call_ext_id: callExtId,
1900
+ log_conversation_ext_id: str(m.log_conversation_ext_id)
1901
+ });
1902
+ return true;
1903
+ case "call.knock": {
1904
+ const knock = m;
1905
+ if (!callExtId) return true;
1906
+ callSession.addKnock({
1907
+ callExtId,
1908
+ knockId: knock.knock_id,
1909
+ displayName: knock.display_name,
1910
+ userExtId: knock.user_ext_id
1911
+ });
1912
+ return true;
1913
+ }
1914
+ case "call.knock_resolved": {
1915
+ const knockId = str(m.knock_id);
1916
+ if (knockId) callSession.removeKnock(knockId);
1917
+ return true;
1918
+ }
1919
+ case "call.recording": {
1920
+ if (callExtId)
1921
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recordingsOf(callExtId) });
1922
+ const state2 = browser.calls.recordingStateFrom(m);
1923
+ relay("call.recording", callExtId && state2 ? { ...state2, call_ext_id: callExtId } : null);
1924
+ return true;
1925
+ }
1926
+ case "call.recording_updated": {
1927
+ if (callExtId)
1928
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recordingsOf(callExtId) });
1929
+ return true;
1930
+ }
1931
+ case "call.recording_deleted": {
1932
+ if (callExtId)
1933
+ void queryClient.invalidateQueries({ queryKey: chunkVLK52VXC_cjs.callQueryKeys.recordingsOf(callExtId) });
1934
+ const recordingExtId = str(m.recording_ext_id);
1935
+ relay(
1936
+ "call.recording_deleted",
1937
+ callExtId && recordingExtId ? { call_ext_id: callExtId, recording_ext_id: recordingExtId } : null
1938
+ );
1939
+ return true;
1940
+ }
1941
+ case "call.transcription": {
1942
+ const state2 = browser.calls.transcriptionStateFrom(m);
1943
+ relay("call.transcription", callExtId && state2 ? { ...state2, call_ext_id: callExtId } : null);
1944
+ return true;
1945
+ }
1946
+ case "call.webinar":
1947
+ relay(
1948
+ "call.webinar",
1949
+ callExtId && typeof m.live === "boolean" ? {
1950
+ type: "call.webinar",
1951
+ call_ext_id: callExtId,
1952
+ live: m.live,
1953
+ chat: m.chat === "everyone" ? "everyone" : "panelists"
1954
+ } : null
1955
+ );
1956
+ return true;
1957
+ case "call.muted":
1958
+ relay("call.muted", mutedNoticeFromEvent(m));
1959
+ return true;
1960
+ default:
1961
+ return false;
1962
+ }
1963
+ }
1964
+ function useCallLiveUpdates(options = {}) {
1965
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
1966
+ const queryClient = reactQuery.useQueryClient();
1967
+ const ws = react.useContext(ArbiWsContext);
1968
+ const latest = react.useRef({ ...options, me: options.me ?? null });
1969
+ latest.current = {
1970
+ ...options,
1971
+ me: options.me ?? (arbi.isLoggedIn ? arbi.user.identity()?.externalId ?? null : null)
1972
+ };
1973
+ react.useEffect(
1974
+ () => ws?.subscribe((message) => {
1975
+ if (message.type.startsWith("call.")) applyCallEvent(queryClient, message, latest.current);
1976
+ }),
1977
+ [ws, queryClient]
1978
+ );
1979
+ }
1980
+ async function postToThread(arbi, conversationExtId, newThreadTitle, content) {
1981
+ const posted = await arbi.conversations.postMessage({
1982
+ content,
1983
+ assistant_mode: "mentioned",
1984
+ ...conversationExtId ? { conversation_ext_id: conversationExtId } : { title: newThreadTitle }
1985
+ });
1986
+ return posted?.conversation_ext_id ?? null;
1987
+ }
1988
+ function postTranscriptToThread(arbi, params) {
1989
+ return postToThread(
1990
+ arbi,
1991
+ params.conversationExtId,
1992
+ `Transcript: ${params.title?.trim() || "Meeting"}`,
1993
+ formatTranscriptMarkdown({ title: params.title, lines: params.lines })
1994
+ );
1995
+ }
1996
+ function postRecordingDocsToThread(arbi, params) {
1997
+ const meeting = params.title?.trim() || "Meeting";
1998
+ const content = [
1999
+ `**Recording: ${meeting}**`,
2000
+ "",
2001
+ ...params.docExtIds.map((id) => `- \`${id}\``)
2002
+ ].join("\n");
2003
+ return postToThread(arbi, params.conversationExtId, `Recording: ${meeting}`, content);
2004
+ }
2005
+ async function saveRecordingFilesToThread(arbi, params) {
2006
+ const workspaceKey = await arbi.workspaces.key(params.workspaceExtId);
2007
+ params.onUploading?.();
2008
+ const result = await browser.documents.uploadDocumentsDirect(
2009
+ arbi.getClient(),
2010
+ workspaceKey,
2011
+ await Promise.all(
2012
+ params.files.map(async (file) => ({
2013
+ name: file.name,
2014
+ data: new Uint8Array(await file.arrayBuffer()),
2015
+ contentType: file.type || browser.documents.mimeFromName(file.name)
2016
+ }))
2017
+ ),
2018
+ { shared: true }
2019
+ );
2020
+ if (!result.doc_ext_ids.length) {
2021
+ throw new Error(
2022
+ `The files were not uploaded${result.skipped[0] ? `: ${result.skipped[0].reason}` : ""}`
2023
+ );
2024
+ }
2025
+ return postRecordingDocsToThread(arbi, {
2026
+ conversationExtId: params.conversationExtId,
2027
+ title: params.title,
2028
+ docExtIds: result.doc_ext_ids
2029
+ });
2030
+ }
2031
+ function useSaveToThread() {
2032
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
2033
+ const queryClient = reactQuery.useQueryClient();
2034
+ return react.useMemo(() => {
2035
+ const thenRefresh = async (run) => {
2036
+ const result = await run;
2037
+ void invalidateConversationLists(queryClient);
2038
+ return result;
2039
+ };
2040
+ return {
2041
+ transcript: (params) => thenRefresh(postTranscriptToThread(arbi, params)),
2042
+ recording: (params) => thenRefresh(saveRecordingFilesToThread(arbi, params))
2043
+ };
2044
+ }, [arbi, queryClient]);
2045
+ }
2046
+ function callLink(callExtId, key, linkVersion) {
2047
+ return client.buildCallLink(window.location.origin, callExtId, key, linkVersion);
2048
+ }
2049
+ function alreadyInCall(callExtId) {
2050
+ const active = callSession.getState().active;
2051
+ if (!active || active.callExtId === callExtId) return false;
2052
+ chunkVAMPYLQ4_cjs.notify.warning("You are already in a call. Leave it first.");
2053
+ return true;
2054
+ }
2055
+ function fail(err, what = "start the call") {
2056
+ console.error(`[calls] failed to ${what}`, err);
2057
+ const message = err instanceof Error ? err.message : "Unknown error";
2058
+ chunkVAMPYLQ4_cjs.notify.error(`Could not ${what}: ${message}`);
2059
+ }
2060
+ function callContext(call) {
2061
+ return {
2062
+ chatExtId: call.chat_ext_id ?? null,
2063
+ logConversationExtId: call.log_conversation_ext_id ?? null,
2064
+ meetingConversationExtId: call.meeting_conversation_ext_id ?? null,
2065
+ lockedWorkspaceExtId: call.locked_workspace_ext_id ?? null
2066
+ };
2067
+ }
2068
+ async function sendInviteLinks(arbi, callExtId, key, linkVersion, invites) {
2069
+ let sent = 0;
2070
+ for (const invite of invites) {
2071
+ try {
2072
+ await arbi.calls.inviteLinks.create(callExtId, {
2073
+ contact_ext_id: invite.contactExtId,
2074
+ link: callLink(callExtId, key, linkVersion)
2075
+ });
2076
+ sent += 1;
2077
+ } catch (err) {
2078
+ fail(err, `invite ${invite.name || "a contact"}`);
2079
+ }
2080
+ }
2081
+ if (sent) chunkVAMPYLQ4_cjs.notify.success(`Sent ${sent} ${sent === 1 ? "invitation" : "invitations"}`);
2082
+ return sent;
2083
+ }
2084
+ async function startCall(arbi, opts) {
2085
+ if (alreadyInCall()) return false;
2086
+ try {
2087
+ const {
2088
+ call,
2089
+ key,
2090
+ title,
2091
+ sealedKeys: ringOnJoin
2092
+ } = await arbi.calls.start({ ...opts.context, title: opts.title, invitees: opts.ring });
2093
+ callSession.setActiveCall({
2094
+ callExtId: call.external_id,
2095
+ key,
2096
+ linkVersion: call.link_version,
2097
+ title,
2098
+ isCreator: call.is_creator,
2099
+ ...callContext(call),
2100
+ phase: "prejoin",
2101
+ tokenResponse: null,
2102
+ choices: null,
2103
+ knock: null,
2104
+ ringOnJoin: Object.keys(ringOnJoin).length ? ringOnJoin : null
2105
+ });
2106
+ if (opts.invites?.length) {
2107
+ void sendInviteLinks(arbi, call.external_id, key, call.link_version, opts.invites);
2108
+ }
2109
+ return true;
2110
+ } catch (err) {
2111
+ fail(err);
2112
+ return false;
2113
+ }
2114
+ }
2115
+ function startThreadCall(arbi, opts) {
2116
+ return startCall(arbi, {
2117
+ context: { threadExtId: opts.threadExtId },
2118
+ title: opts.title,
2119
+ ring: opts.ring
2120
+ });
2121
+ }
2122
+ function startChatCall(arbi, opts) {
2123
+ return startCall(arbi, {
2124
+ context: { chatExtId: opts.chatExtId },
2125
+ title: opts.title,
2126
+ ring: opts.ring
2127
+ });
2128
+ }
2129
+ async function startDmCall(arbi, peer) {
2130
+ if (alreadyInCall()) return false;
2131
+ if (!peer.encryption_public_key) {
2132
+ fail(new Error("This person cannot receive encrypted calls"));
2133
+ return false;
2134
+ }
2135
+ let chatExtId;
2136
+ try {
2137
+ chatExtId = (await arbi.chats.openDirect(peer.external_id)).external_id;
2138
+ } catch (err) {
2139
+ fail(err);
2140
+ return false;
2141
+ }
2142
+ return startChatCall(arbi, { chatExtId, title: peer.name ?? null, ring: [peer] });
2143
+ }
2144
+ function startContactsCall(arbi, opts) {
2145
+ return startCall(arbi, { context: {}, title: opts.title, ring: opts.ring, invites: opts.invites });
2146
+ }
2147
+ async function openCall(arbi, opts) {
2148
+ if (alreadyInCall(opts.callExtId)) return false;
2149
+ try {
2150
+ const { call, key, title } = await arbi.calls.open(opts.callExtId, opts.key);
2151
+ callSession.setActiveCall({
2152
+ callExtId: call.external_id,
2153
+ key,
2154
+ linkVersion: opts.linkVersion ?? call.link_version,
2155
+ title,
2156
+ isCreator: call.is_creator,
2157
+ ...callContext(call),
2158
+ phase: "prejoin",
2159
+ tokenResponse: null,
2160
+ choices: null,
2161
+ knock: null,
2162
+ ringOnJoin: null,
2163
+ inviteToken: opts.inviteToken ?? null
2164
+ });
2165
+ return true;
2166
+ } catch (err) {
2167
+ fail(err, "open the call");
2168
+ return false;
2169
+ }
2170
+ }
2171
+ async function acceptRing(arbi, ring) {
2172
+ const current = callSession.getState().active;
2173
+ if (current && current.callExtId !== ring.call_ext_id) callSession.endActiveCall();
2174
+ try {
2175
+ const { key, token, title } = await arbi.calls.answer(ring);
2176
+ callSession.setActiveCall({
2177
+ callExtId: ring.call_ext_id,
2178
+ key,
2179
+ linkVersion: ring.link_version,
2180
+ title: title || ring.caller_name,
2181
+ isCreator: false,
2182
+ chatExtId: ring.chat_ext_id ?? null,
2183
+ logConversationExtId: ring.log_conversation_ext_id ?? null,
2184
+ meetingConversationExtId: ring.meeting_conversation_ext_id ?? null,
2185
+ lockedWorkspaceExtId: ring.context === "thread" ? ring.workspace_ext_id ?? null : null,
2186
+ phase: "connected",
2187
+ tokenResponse: token,
2188
+ choices: DEFAULT_JOIN_CHOICES,
2189
+ knock: null,
2190
+ ringOnJoin: null
2191
+ });
2192
+ return true;
2193
+ } catch (err) {
2194
+ fail(err, "join the call");
2195
+ callSession.removeIncomingCall(ring.call_ext_id);
2196
+ return false;
2197
+ }
2198
+ }
2199
+ function declineRing(arbi, ring) {
2200
+ callSession.removeIncomingCall(ring.call_ext_id);
2201
+ arbi.calls.decline(ring.call_ext_id).catch((err) => console.warn("[calls] decline failed", err));
2202
+ }
2203
+ var KNOCK_POLL_MS = 2e3;
2204
+ async function waitForAdmission(arbi, callExtId, knock, signal) {
2205
+ for (; ; ) {
2206
+ if (signal.aborted) throw new DOMException("Stopped waiting", "AbortError");
2207
+ await new Promise((resolve) => setTimeout(resolve, KNOCK_POLL_MS));
2208
+ if (signal.aborted) throw new DOMException("Stopped waiting", "AbortError");
2209
+ const state2 = await arbi.calls.pollKnock(callExtId, knock.knock_id);
2210
+ if (state2.status === "admitted" && state2.token) return state2.token;
2211
+ if (state2.status === "denied") throw new browser.CallApiError("The host declined your request.", 403);
2212
+ if (state2.status === "expired") throw new browser.CallApiError("Nobody let you in. Try again.", 410);
2213
+ }
2214
+ }
2215
+ async function joinFromPreJoin(arbi, choices) {
2216
+ const active = callSession.getState().active;
2217
+ if (!active) return;
2218
+ const { callExtId, linkVersion, inviteToken } = active;
2219
+ const update2 = (patch) => callSession.updateActiveCall(callExtId, patch);
2220
+ try {
2221
+ let tokenResponse;
2222
+ try {
2223
+ tokenResponse = await arbi.calls.token(callExtId, linkVersion, inviteToken);
2224
+ } catch (err) {
2225
+ if (!(err instanceof browser.CallApiError && err.code === "knock_required")) throw err;
2226
+ const knock = await arbi.calls.knock(callExtId, linkVersion);
2227
+ if (knock.status === "admitted" && knock.token) tokenResponse = knock.token;
2228
+ else {
2229
+ const controller = new AbortController();
2230
+ update2({ phase: "knocking", choices, knock: { abort: () => controller.abort() } });
2231
+ tokenResponse = await waitForAdmission(arbi, callExtId, knock, controller.signal);
2232
+ }
2233
+ }
2234
+ if (callSession.getState().active?.callExtId !== callExtId) return;
2235
+ update2({ phase: "connected", tokenResponse, choices, knock: null });
2236
+ const ring = active.ringOnJoin;
2237
+ if (ring && Object.keys(ring).length) {
2238
+ update2({ ringOnJoin: null });
2239
+ await arbi.calls.ring(callExtId, ring, linkVersion).catch((err) => console.warn("[calls] ring failed", err));
2240
+ }
2241
+ } catch (err) {
2242
+ if (err instanceof DOMException && err.name === "AbortError") return;
2243
+ if (err instanceof browser.CallApiError && err.code === "webinar_not_live") {
2244
+ update2({ phase: "webinar-waiting", choices, knock: null });
2245
+ return;
2246
+ }
2247
+ fail(err, "join the call");
2248
+ if (callSession.getState().active?.callExtId === callExtId) {
2249
+ callSession.endActiveCall();
2250
+ }
2251
+ }
2252
+ }
2253
+ var CALL_WEBINAR_TOPIC = "arbi.webinar";
2254
+ var AUDIENCE_CHOICES = { audioEnabled: false, videoEnabled: false };
2255
+ var isHand = (h) => !!h && typeof h === "object" && typeof h.identity === "string" && typeof h.raised_at === "string";
2256
+ function parseWebinarPacket(payload, fromParticipant) {
2257
+ if (fromParticipant) return null;
2258
+ let raw;
2259
+ try {
2260
+ raw = JSON.parse(new TextDecoder().decode(payload));
2261
+ } catch {
2262
+ return null;
2263
+ }
2264
+ if (!raw || typeof raw !== "object") return null;
2265
+ const p = raw;
2266
+ switch (p.type) {
2267
+ case "state":
2268
+ if (typeof p.live !== "boolean") return null;
2269
+ return {
2270
+ type: "state",
2271
+ live: p.live,
2272
+ live_at: typeof p.live_at === "string" ? p.live_at : null,
2273
+ chat: p.chat === "everyone" ? "everyone" : "panelists"
2274
+ };
2275
+ case "hands":
2276
+ return {
2277
+ type: "hands",
2278
+ hands: Array.isArray(p.hands) ? p.hands.filter(isHand).map((h) => ({ ...h, name: String(h.name ?? "") })) : []
2279
+ };
2280
+ case "questions":
2281
+ case "promoted":
2282
+ case "demoted":
2283
+ return { type: p.type };
2284
+ default:
2285
+ return null;
2286
+ }
2287
+ }
2288
+ var UNREADABLE = "(This question could not be decrypted.)";
2289
+ function sealQuestionText(text, key) {
2290
+ return client.encryptCallTitle(text, key);
2291
+ }
2292
+ async function openQuestion(q, key) {
2293
+ const [text, answerText] = await Promise.all([
2294
+ client.decryptCallTitle(q.body, key),
2295
+ q.answer ? client.decryptCallTitle(q.answer, key) : Promise.resolve(null)
2296
+ ]);
2297
+ return { ...q, text: text ?? UNREADABLE, answerText };
2298
+ }
2299
+ function markRejoining(callExtId, on = true) {
2300
+ callSession.updateActiveCall(callExtId, { rejoining: on });
2301
+ }
2302
+ async function rejoinAsAudience(arbi, callExtId) {
2303
+ if (callSession.getState().active?.callExtId !== callExtId) return;
2304
+ markRejoining(callExtId);
2305
+ try {
2306
+ await joinFromPreJoin(arbi, AUDIENCE_CHOICES);
2307
+ } finally {
2308
+ markRejoining(callExtId, false);
2309
+ }
2310
+ }
2311
+
2312
+ // src/calls/read-only.ts
2313
+ function isWorkspaceGuestOf(workspaces, workspaceExtId, me) {
2314
+ if (!workspaceExtId || !me || !workspaces) return false;
2315
+ const workspace = workspaces.find((w) => w.external_id === workspaceExtId);
2316
+ return workspace?.users?.find((wu) => wu.user.external_id === me)?.role === "guest";
2317
+ }
2318
+ function useMeetingReadOnly(lockedWorkspaceExtId) {
2319
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
2320
+ const me = arbi.isLoggedIn ? arbi.user.identity()?.externalId ?? null : null;
2321
+ const { data: workspaces } = chunk5B4PPJNW_cjs.useWorkspaces({
2322
+ enabled: !!lockedWorkspaceExtId && arbi.isLoggedIn
2323
+ });
2324
+ return isWorkspaceGuestOf(
2325
+ workspaces,
2326
+ lockedWorkspaceExtId,
2327
+ me
2328
+ );
2329
+ }
2330
+
2331
+ // src/calls/gate.ts
2332
+ function useCallsEnabled() {
2333
+ const serverEnabled = useServerCallsEnabled();
2334
+ const switchedOn = chunkQQ7SCJRY_cjs.useArbiHost().calls?.useEnabled?.() ?? true;
2335
+ return serverEnabled && switchedOn;
2336
+ }
2337
+ function useCanHostCalls() {
2338
+ const callsEnabled = useCallsEnabled();
2339
+ const entitled = useIsEntitled("host_calls");
2340
+ return callsEnabled && entitled;
2341
+ }
2342
+ function useOpenCallMeetingChat() {
2343
+ const arbi = chunkQQ7SCJRY_cjs.useArbi();
2344
+ const queryClient = reactQuery.useQueryClient();
2345
+ const open = chunkQQ7SCJRY_cjs.useArbiHost().calls?.openMeetingChat;
2346
+ return react.useCallback(
2347
+ async (target) => {
2348
+ try {
2349
+ const ref = await resolveMeetingChat(arbi, queryClient, target);
2350
+ open?.(ref);
2351
+ } catch (err) {
2352
+ console.warn("[calls] could not open the meeting chat", err);
2353
+ chunkVAMPYLQ4_cjs.notify.error(
2354
+ `Could not open the meeting chat: ${err instanceof Error ? err.message : "unknown error"}`
2355
+ );
2356
+ }
2357
+ },
2358
+ [arbi, queryClient, open]
2359
+ );
2360
+ }
2361
+
2362
+ exports.AUDIENCE_CHOICES = AUDIENCE_CHOICES;
2363
+ exports.ArbiWsContext = ArbiWsContext;
2364
+ exports.CALL_CAPTION_TOPIC = CALL_CAPTION_TOPIC;
2365
+ exports.CALL_CHAT_MAX_CHARS = CALL_CHAT_MAX_CHARS;
2366
+ exports.CALL_CHAT_TOPIC = CALL_CHAT_TOPIC;
2367
+ exports.CALL_MODERATION_TOPIC = CALL_MODERATION_TOPIC;
2368
+ exports.CALL_RECORDING_TOPIC = CALL_RECORDING_TOPIC;
2369
+ exports.CALL_TRANSCRIPTION_TOPIC = CALL_TRANSCRIPTION_TOPIC;
2370
+ exports.CALL_WEBINAR_TOPIC = CALL_WEBINAR_TOPIC;
2371
+ exports.CAPTION_MAX_CHARS = CAPTION_MAX_CHARS;
2372
+ exports.COMPOSITE_AUDIO_BITS_PER_SECOND = COMPOSITE_AUDIO_BITS_PER_SECOND;
2373
+ exports.COMPOSITE_VIDEO_BITS_PER_SECOND = COMPOSITE_VIDEO_BITS_PER_SECOND;
2374
+ exports.DEFAULT_JOIN_CHOICES = DEFAULT_JOIN_CHOICES;
2375
+ exports.EMPTY_CALL_SESSION = EMPTY_CALL_SESSION;
2376
+ exports.EXPORT_SAMPLE_RATE = EXPORT_SAMPLE_RATE;
2377
+ exports.HISTORY_LIMIT = HISTORY_LIMIT;
2378
+ exports.LIVE_SEGMENTER = LIVE_SEGMENTER;
2379
+ exports.MAX_AVATAR_FILE_BYTES = MAX_AVATAR_FILE_BYTES;
2380
+ exports.MUTED_DEDUPE_MS = MUTED_DEDUPE_MS;
2381
+ exports.PLAYBACK_LOOKAHEAD_MS = PLAYBACK_LOOKAHEAD_MS;
2382
+ exports.READ_ONLY_MEETING_TEXT = READ_ONLY_MEETING_TEXT;
2383
+ exports.RECORDING_CHUNK_MS = RECORDING_CHUNK_MS;
2384
+ exports.RECORDING_SEGMENTER = RECORDING_SEGMENTER;
2385
+ exports.SEGMENT_FRAME_MS = SEGMENT_FRAME_MS;
2386
+ exports.SEGMENT_ID_PATTERN = SEGMENT_ID_PATTERN;
2387
+ exports.SEGMENT_PRE_ROLL_MS = SEGMENT_PRE_ROLL_MS;
2388
+ exports.SHORT_PIECE_MERGE_GAP_MS = SHORT_PIECE_MERGE_GAP_MS;
2389
+ exports.SPEAKER_AUDIO_BITS_PER_SECOND = SPEAKER_AUDIO_BITS_PER_SECOND;
2390
+ exports.TrackUploader = TrackUploader;
2391
+ exports.UPLOAD_ATTEMPTS = UPLOAD_ATTEMPTS;
2392
+ exports.UPLOAD_BACKOFF_MS = UPLOAD_BACKOFF_MS;
2393
+ exports.acceptRing = acceptRing;
2394
+ exports.addConversationToList = addConversationToList;
2395
+ exports.appendToThread = appendToThread;
2396
+ exports.applyAgentDmStatus = applyAgentDmStatus;
2397
+ exports.applyCallEvent = applyCallEvent;
2398
+ exports.applyChatEvent = applyChatEvent;
2399
+ exports.applyChatMessage = applyChatMessage;
2400
+ exports.applyChatRead = applyChatRead;
2401
+ exports.applyChatUpdated = applyChatUpdated;
2402
+ exports.arbiAccountClient = arbiAccountClient;
2403
+ exports.buildMeetingChatBody = buildMeetingChatBody;
2404
+ exports.cachedChat = cachedChat;
2405
+ exports.cachedChats = cachedChats;
2406
+ exports.callLink = callLink;
2407
+ exports.callMemberKeys = callMemberKeys;
2408
+ exports.callSession = callSession;
2409
+ exports.chatByExtId = chatByExtId;
2410
+ exports.chatHasLiveCall = chatHasLiveCall;
2411
+ exports.chatLiveCallId = chatLiveCallId;
2412
+ exports.chatTranscriptRef = chatTranscriptRef;
2413
+ exports.clearMeetingChatCache = clearMeetingChatCache;
2414
+ exports.clearTrackUploaders = clearTrackUploaders;
2415
+ exports.clockTime = clockTime;
2416
+ exports.compositeFiles = compositeFiles;
2417
+ exports.compositeTrack = compositeTrack;
2418
+ exports.conversationKeyForCall = conversationKeyForCall;
2419
+ exports.createMutedNotifier = createMutedNotifier;
2420
+ exports.createTrackCutter = createTrackCutter;
2421
+ exports.cutAtPauses = cutAtPauses;
2422
+ exports.declineRing = declineRing;
2423
+ exports.decodeCallChatPacket = decodeCallChatPacket;
2424
+ exports.decodeCaptionPacket = decodeCaptionPacket;
2425
+ exports.decodeMono16k = decodeMono16k;
2426
+ exports.decryptPart = decryptPart;
2427
+ exports.deleteChatMessage = deleteChatMessage;
2428
+ exports.dropFromThread = dropFromThread;
2429
+ exports.encodeCallChatPacket = encodeCallChatPacket;
2430
+ exports.encodeCaptionPacket = encodeCaptionPacket;
2431
+ exports.encodeWav = encodeWav;
2432
+ exports.encryptPart = encryptPart;
2433
+ exports.ensureMeetingChat = ensureMeetingChat;
2434
+ exports.entitlementRefusal = entitlementRefusal;
2435
+ exports.extensionFor = extensionFor;
2436
+ exports.fetchPart = fetchPart;
2437
+ exports.fileSafe = fileSafe;
2438
+ exports.findConversation = findConversation;
2439
+ exports.floatToWav = floatToWav;
2440
+ exports.formatTranscriptMarkdown = formatTranscriptMarkdown;
2441
+ exports.getOpenChat = getOpenChat;
2442
+ exports.hasRecordingTranscript = hasRecordingTranscript;
2443
+ exports.invalidateCall = invalidateCall;
2444
+ exports.invalidateConversationDetails = invalidateConversationDetails;
2445
+ exports.invalidateConversationLists = invalidateConversationLists;
2446
+ exports.isConversationListKey = isConversationListKey;
2447
+ exports.isConversationShared = isConversationShared;
2448
+ exports.isKnownSoloConversation = isKnownSoloConversation;
2449
+ exports.isRecordingOver = isRecordingOver;
2450
+ exports.isRecordingSegmentId = isRecordingSegmentId;
2451
+ exports.isRetryable = isRetryable;
2452
+ exports.isWorkspaceGuestOf = isWorkspaceGuestOf;
2453
+ exports.joinFromPreJoin = joinFromPreJoin;
2454
+ exports.knownMeetingChat = knownMeetingChat;
2455
+ exports.loadMeetingHistory = loadMeetingHistory;
2456
+ exports.markRejoining = markRejoining;
2457
+ exports.meetingChatRefFrom = meetingChatRefFrom;
2458
+ exports.meetingRefForCall = meetingRefForCall;
2459
+ exports.mergeChatLines = mergeChatLines;
2460
+ exports.mutedNoticeFromEvent = mutedNoticeFromEvent;
2461
+ exports.mutedNoticeFromPacket = mutedNoticeFromPacket;
2462
+ exports.mutedNoticeText = mutedNoticeText;
2463
+ exports.myChatId = myChatId;
2464
+ exports.newPacketId = newPacketId;
2465
+ exports.newSegmentId = newSegmentId;
2466
+ exports.newTrackKey = newTrackKey;
2467
+ exports.nextSeqAfter = nextSeqAfter;
2468
+ exports.onCallEvent = onCallEvent;
2469
+ exports.openCall = openCall;
2470
+ exports.openQuestion = openQuestion;
2471
+ exports.openRecording = openRecording;
2472
+ exports.parseWebinarPacket = parseWebinarPacket;
2473
+ exports.partKey = partKey;
2474
+ exports.partOffsetMs = partOffsetMs;
2475
+ exports.partsDue = partsDue;
2476
+ exports.patchConversation = patchConversation;
2477
+ exports.patchConversationList = patchConversationList;
2478
+ exports.persistMeetingMessage = persistMeetingMessage;
2479
+ exports.persistTranscriptSegment = persistTranscriptSegment;
2480
+ exports.playheadAt = playheadAt;
2481
+ exports.postRecordingDocsToThread = postRecordingDocsToThread;
2482
+ exports.postTranscriptToThread = postTranscriptToThread;
2483
+ exports.recordingFiles = recordingFiles;
2484
+ exports.recordingWindowsOf = recordingWindowsOf;
2485
+ exports.rejoinAsAudience = rejoinAsAudience;
2486
+ exports.removeChat = removeChat;
2487
+ exports.removeConversationFromLists = removeConversationFromLists;
2488
+ exports.resetCallSession = resetCallSession;
2489
+ exports.resolveMeetingChat = resolveMeetingChat;
2490
+ exports.saveRecordingFilesToThread = saveRecordingFilesToThread;
2491
+ exports.schedulePart = schedulePart;
2492
+ exports.sealQuestionText = sealQuestionText;
2493
+ exports.setOpenChat = setOpenChat;
2494
+ exports.sortTranscriptMessages = sortTranscriptMessages;
2495
+ exports.sortedParts = sortedParts;
2496
+ exports.speakerTracks = speakerTracks;
2497
+ exports.speakerWav = speakerWav;
2498
+ exports.splitIntoFiles = splitIntoFiles;
2499
+ exports.standalone = standalone;
2500
+ exports.startChatCall = startChatCall;
2501
+ exports.startContactsCall = startContactsCall;
2502
+ exports.startDmCall = startDmCall;
2503
+ exports.startThreadCall = startThreadCall;
2504
+ exports.startsMediaFile = startsMediaFile;
2505
+ exports.storeTranscriptSegment = storeTranscriptSegment;
2506
+ exports.stripSpeakerPrefix = stripSpeakerPrefix;
2507
+ exports.supersedeLiveTranscript = supersedeLiveTranscript;
2508
+ exports.supersededTranscriptLines = supersededTranscriptLines;
2509
+ exports.threadHasLiveCall = threadHasLiveCall;
2510
+ exports.threadLiveCallId = threadLiveCallId;
2511
+ exports.threadTranscriptLines = threadTranscriptLines;
2512
+ exports.threadTranscriptRef = threadTranscriptRef;
2513
+ exports.threadTranscriptText = threadTranscriptText;
2514
+ exports.timelineDurationMs = timelineDurationMs;
2515
+ exports.timelineOf = timelineOf;
2516
+ exports.toProfileView = toProfileView;
2517
+ exports.trackUploaderFor = trackUploaderFor;
2518
+ exports.transcribeRecording = transcribeRecording;
2519
+ exports.transcriptPersistRole = transcriptPersistRole;
2520
+ exports.transcriptSegmentOf = transcriptSegmentOf;
2521
+ exports.unwrapTrackKey = unwrapTrackKey;
2522
+ exports.upsertChat = upsertChat;
2523
+ exports.useAccountClient = useAccountClient;
2524
+ exports.useArbiWsContext = useArbiWsContext;
2525
+ exports.useAvatarCrop = useAvatarCrop;
2526
+ exports.useCall = useCall;
2527
+ exports.useCallInviteLinks = useCallInviteLinks;
2528
+ exports.useCallLiveUpdates = useCallLiveUpdates;
2529
+ exports.useCallRecording = useCallRecording;
2530
+ exports.useCallRecordings = useCallRecordings;
2531
+ exports.useCallSession = useCallSession;
2532
+ exports.useCallTranscriptionAvailable = useCallTranscriptionAvailable;
2533
+ exports.useCallsConfig = useCallsConfig;
2534
+ exports.useCallsEnabled = useCallsEnabled;
2535
+ exports.useCanHostCalls = useCanHostCalls;
2536
+ exports.useEntitlements = useEntitlements;
2537
+ exports.useIsEntitled = useIsEntitled;
2538
+ exports.useMeetingReadOnly = useMeetingReadOnly;
2539
+ exports.useNameEditor = useNameEditor;
2540
+ exports.useOpenCallMeetingChat = useOpenCallMeetingChat;
2541
+ exports.useProfile = useProfile;
2542
+ exports.useRecordingActions = useRecordingActions;
2543
+ exports.useRecordingWindows = useRecordingWindows;
2544
+ exports.useRevokeCallInviteLink = useRevokeCallInviteLink;
2545
+ exports.useSaveToThread = useSaveToThread;
2546
+ exports.useServerCallsEnabled = useServerCallsEnabled;
2547
+ exports.useUpdateProfile = useUpdateProfile;
2548
+ exports.wrapTrackKey = wrapTrackKey;
2549
+ exports.writeSamples = writeSamples;
2550
+ //# sourceMappingURL=chunk-3J7MEBOW.cjs.map
2551
+ //# sourceMappingURL=chunk-3J7MEBOW.cjs.map