@fabriktor/fx 0.0.166 → 0.0.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.
@@ -1,4 +1,5 @@
1
1
  import type { CallsOperator, NotificationsOperator } from "@fabriktor/client";
2
+ import { CallSession, type CallSessionOptions } from "./session.js";
2
3
  export type MintVideoTokenOptions = Parameters<CallsOperator["mintVideoToken"]>[0];
3
4
  export type RelayNotificationOptions = Parameters<NotificationsOperator["relayNotification"]>[0];
4
5
  export type StartCallOptions = {
@@ -17,6 +18,7 @@ export type CallsFXOptions = {
17
18
  notifications: NotificationsOperator;
18
19
  };
19
20
  export interface CallsFXOperator {
21
+ createSession(opts: CallSessionOptions): CallSession;
20
22
  startCall(opts: StartCallOptions): Promise<string>;
21
23
  answerCall(opts: AnswerCallOptions): Promise<string>;
22
24
  cancelCall(opts: CancelCallOptions): Promise<void>;
@@ -25,6 +27,7 @@ export declare class CallsFX implements CallsFXOperator {
25
27
  private calls;
26
28
  private notifications;
27
29
  constructor(opts: CallsFXOptions);
30
+ createSession(opts: CallSessionOptions): CallSession;
28
31
  startCall(opts: StartCallOptions): Promise<string>;
29
32
  answerCall(opts: AnswerCallOptions): Promise<string>;
30
33
  cancelCall(opts: CancelCallOptions): Promise<void>;
@@ -4,6 +4,7 @@
4
4
  // not use this file except in compliance with the License. You may obtain
5
5
  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
6
  import { errResolveFailed } from "../core/err.js";
7
+ import { CallSession } from "./session.js";
7
8
  const resourceVideoToken = "video_token";
8
9
  const msgUnableToMintVideoToken = "Unable to mint video token.";
9
10
  export class CallsFX {
@@ -13,6 +14,12 @@ export class CallsFX {
13
14
  this.calls = opts.calls;
14
15
  this.notifications = opts.notifications;
15
16
  }
17
+ createSession(opts) {
18
+ return new CallSession({
19
+ ...opts,
20
+ calls: this.calls,
21
+ });
22
+ }
16
23
  async startCall(opts) {
17
24
  const token = await this.requireVideoToken(opts.mint);
18
25
  await this.notifications.relayNotification(opts.notification);
@@ -0,0 +1,90 @@
1
+ import type { CallsOperator } from "@fabriktor/client";
2
+ import { CallModeAudio, CallModeVideo } from "@fabriktor/schema";
3
+ export declare const callsNotificationKey = "calls.events.received";
4
+ export declare const callRingTimeoutMS = 60000;
5
+ export type CallMode = typeof CallModeAudio | typeof CallModeVideo;
6
+ export type CallPhase = "idle" | "incoming" | "connecting" | "ringing" | "connected" | "reconnecting";
7
+ export type CallParticipant = {
8
+ id: string;
9
+ user_id: string;
10
+ local: boolean;
11
+ audio: boolean;
12
+ video: boolean;
13
+ };
14
+ export type CallMediaState = {
15
+ participants: readonly CallParticipant[];
16
+ reconnecting: boolean;
17
+ };
18
+ export interface CallMediaConnection {
19
+ disconnect(): void;
20
+ microphone(enabled: boolean): Promise<void>;
21
+ camera(enabled: boolean): Promise<void>;
22
+ }
23
+ export interface CallMediaAdapter {
24
+ connect(opts: {
25
+ token: string;
26
+ call: CallInvitation;
27
+ room_id: string;
28
+ video: boolean;
29
+ signal: AbortSignal;
30
+ on_change: (state: CallMediaState) => void;
31
+ on_disconnect: (error?: unknown) => void;
32
+ }): Promise<CallMediaConnection>;
33
+ }
34
+ export type CallInvitation = {
35
+ id: string;
36
+ room_id: string;
37
+ caller_id: string;
38
+ mode: CallMode;
39
+ ticket: string;
40
+ expires_at: number;
41
+ };
42
+ export type CallSessionState = {
43
+ phase: CallPhase;
44
+ call: CallInvitation | null;
45
+ participants: readonly CallParticipant[];
46
+ microphone: boolean;
47
+ camera: boolean;
48
+ };
49
+ export type CallSessionOptions = {
50
+ owner_id: string;
51
+ device_id: string;
52
+ media: CallMediaAdapter;
53
+ on_change: (state: CallSessionState) => void;
54
+ on_error: (error: unknown) => void;
55
+ };
56
+ export type CallSessionDependencies = CallSessionOptions & {
57
+ calls: CallsOperator;
58
+ };
59
+ export declare class CallSession {
60
+ private opts;
61
+ state: CallSessionState;
62
+ private connection?;
63
+ private connecting;
64
+ private controller?;
65
+ private timer?;
66
+ private recipients;
67
+ private closed;
68
+ private had_remote;
69
+ private disposed;
70
+ private inviting?;
71
+ constructor(opts: CallSessionDependencies);
72
+ start(room_id: string, members: readonly string[], mode: CallMode): Promise<void>;
73
+ receive(data: Readonly<Record<string, string>>): void;
74
+ restore(call: CallInvitation, phase: CallPhase): Promise<void>;
75
+ answer(): Promise<void>;
76
+ end(): Promise<void>;
77
+ microphone(enabled: boolean): Promise<void>;
78
+ camera(enabled: boolean): Promise<void>;
79
+ dispose(): void;
80
+ private begin;
81
+ private connect;
82
+ private access;
83
+ private respond;
84
+ private current;
85
+ private publish;
86
+ private reset;
87
+ private remember;
88
+ private armTimeout;
89
+ private clearTimer;
90
+ }
@@ -0,0 +1,364 @@
1
+ // Copyright (C) Fabriktor, Inc. 2025-present.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License"); you may
4
+ // not use this file except in compliance with the License. You may obtain
5
+ // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ import { CallIDKey, CallTicketKey, CallOwnerIDKey, CallExpiresAtKey, CallActionRing, CallActionAnswer, CallActionEnd, CallStateEnded, CallRingTimeoutMS, CallRoomIDKey, CallSenderIDKey, CallModeKey, CallSignalKey, CallModeAudio, CallModeVideo, CallSignalInvite, CallSignalAnswered, CallSignalCancelled, ColCallsEvents, SvcCalls, } from "@fabriktor/schema";
7
+ import { errValidation, errResolveFailed } from "../core/err.js";
8
+ // Notification keys are preference-map keys, not generated Go constants.
9
+ export const callsNotificationKey = `${SvcCalls}.${ColCallsEvents}.received`;
10
+ export const callRingTimeoutMS = CallRingTimeoutMS;
11
+ const closedCallLimit = 100;
12
+ function idleCallState() {
13
+ return {
14
+ phase: "idle",
15
+ call: null,
16
+ participants: [],
17
+ microphone: true,
18
+ camera: false,
19
+ };
20
+ }
21
+ // One foreground call per authenticated session. Media ownership is independent of views.
22
+ export class CallSession {
23
+ opts;
24
+ state = idleCallState();
25
+ connection;
26
+ connecting = "";
27
+ controller;
28
+ timer;
29
+ recipients = [];
30
+ closed = new Set();
31
+ had_remote = false;
32
+ disposed = false;
33
+ inviting;
34
+ constructor(opts) {
35
+ this.opts = opts;
36
+ }
37
+ async start(room_id, members, mode) {
38
+ if (this.disposed || this.state.call)
39
+ return;
40
+ const recipients = [...new Set(members)].filter((id) => id && id !== this.opts.owner_id);
41
+ if (!room_id || !recipients.length)
42
+ throw errValidation({
43
+ msg: "A call requires a room and another member.",
44
+ });
45
+ const call = {
46
+ id: crypto.randomUUID(),
47
+ room_id,
48
+ caller_id: this.opts.owner_id,
49
+ mode,
50
+ ticket: "",
51
+ expires_at: Date.now() + callRingTimeoutMS,
52
+ };
53
+ this.recipients = recipients;
54
+ this.begin(call, "connecting");
55
+ try {
56
+ const out = await this.opts.calls.startCallSession({
57
+ call_id: call.id,
58
+ room_id,
59
+ device_id: this.opts.device_id,
60
+ user_ids: recipients,
61
+ mode,
62
+ });
63
+ const access = this.access(out.value);
64
+ call.ticket = access.ticket;
65
+ call.expires_at = access.expires_at;
66
+ if (!this.current(call)) {
67
+ await this.respond(call, CallActionEnd);
68
+ return;
69
+ }
70
+ await this.connect(call, access.token);
71
+ if (!this.current(call))
72
+ return;
73
+ // Do not ring recipients until the caller has joined successfully.
74
+ const inviting = this.respond(call, CallActionRing).then(() => { });
75
+ this.inviting = { id: call.id, promise: inviting };
76
+ await inviting;
77
+ if (!this.current(call))
78
+ return;
79
+ if (!this.had_remote)
80
+ this.publish({ phase: "ringing" });
81
+ this.armTimeout(call);
82
+ }
83
+ catch (error) {
84
+ if (this.current(call)) {
85
+ this.reset(call);
86
+ if (call.ticket)
87
+ void this.respond(call, CallActionEnd).catch(this.opts.on_error);
88
+ throw error;
89
+ }
90
+ }
91
+ finally {
92
+ if (this.inviting?.id === call.id)
93
+ this.inviting = undefined;
94
+ }
95
+ }
96
+ receive(data) {
97
+ if (this.disposed)
98
+ return;
99
+ if (data[CallOwnerIDKey] !== this.opts.owner_id)
100
+ return;
101
+ const id = data[CallIDKey], room_id = data[CallRoomIDKey], sender = data[CallSenderIDKey];
102
+ const mode = data[CallModeKey], signal = data[CallSignalKey];
103
+ if (!id ||
104
+ !room_id ||
105
+ !sender ||
106
+ (mode !== CallModeAudio && mode !== CallModeVideo))
107
+ return;
108
+ const call = this.state.call;
109
+ if (signal === CallSignalInvite) {
110
+ if (sender === this.opts.owner_id ||
111
+ this.closed.has(id) ||
112
+ call?.id === id)
113
+ return;
114
+ const ticket = data[CallTicketKey], expires_at = Number(data[CallExpiresAtKey]);
115
+ if (!ticket || !Number.isFinite(expires_at) || expires_at <= Date.now())
116
+ return;
117
+ const incoming = {
118
+ id,
119
+ room_id,
120
+ caller_id: sender,
121
+ mode,
122
+ ticket,
123
+ expires_at,
124
+ };
125
+ if (call) {
126
+ // Busy/decline affects this recipient only, never an entire group.
127
+ this.remember(id);
128
+ void this.respond(incoming, CallActionEnd).catch(this.opts.on_error);
129
+ return;
130
+ }
131
+ this.begin(incoming, "incoming");
132
+ this.armTimeout(incoming);
133
+ return;
134
+ }
135
+ if (signal !== CallSignalCancelled && signal !== CallSignalAnswered)
136
+ return;
137
+ if (!call || call.id !== id || call.room_id !== room_id) {
138
+ this.remember(id);
139
+ return;
140
+ }
141
+ if (sender === this.opts.owner_id) {
142
+ // The accepting device is already connecting; other devices still ring.
143
+ if (this.state.phase === "incoming")
144
+ this.reset(call);
145
+ return;
146
+ }
147
+ if (signal !== CallSignalCancelled)
148
+ return;
149
+ if (sender === call.caller_id &&
150
+ (this.state.phase === "incoming" || this.state.phase === "connecting")) {
151
+ this.reset(call);
152
+ }
153
+ else if (call.caller_id === this.opts.owner_id && !this.had_remote) {
154
+ this.recipients = this.recipients.filter((id) => id !== sender);
155
+ if (!this.recipients.length)
156
+ this.reset(call);
157
+ }
158
+ }
159
+ // Native media can already be connected when the WebView resumes.
160
+ async restore(call, phase) {
161
+ if (this.disposed || this.closed.has(call.id))
162
+ return;
163
+ if (this.state.call && this.state.call.id !== call.id)
164
+ return;
165
+ if (!this.state.call)
166
+ this.begin(call, phase);
167
+ else
168
+ this.publish({ phase });
169
+ const current = this.state.call;
170
+ if ((phase === "connected" || phase === "ringing") &&
171
+ !this.connection &&
172
+ this.connecting !== call.id)
173
+ await this.connect(current, "");
174
+ }
175
+ async answer() {
176
+ const call = this.state.call;
177
+ if (!call || this.state.phase !== "incoming")
178
+ return;
179
+ this.clearTimer();
180
+ this.publish({ phase: "connecting" });
181
+ try {
182
+ const access = await this.respond(call, CallActionAnswer);
183
+ if (!this.current(call)) {
184
+ await this.respond(call, CallActionEnd);
185
+ return;
186
+ }
187
+ await this.connect(call, access.token);
188
+ if (!this.current(call))
189
+ return;
190
+ if (this.current(call)) {
191
+ this.publish({ phase: this.had_remote ? "connected" : "connecting" });
192
+ this.armTimeout(call);
193
+ }
194
+ }
195
+ catch (error) {
196
+ if (this.current(call)) {
197
+ this.reset(call);
198
+ if (call.ticket)
199
+ void this.respond(call, CallActionEnd).catch(this.opts.on_error);
200
+ throw error;
201
+ }
202
+ }
203
+ }
204
+ async end() {
205
+ const call = this.state.call;
206
+ if (!call)
207
+ return;
208
+ const inviting = this.inviting?.id === call.id ? this.inviting.promise : undefined;
209
+ // Release devices immediately, including a pending permission/connect request.
210
+ this.reset(call);
211
+ if (inviting)
212
+ await inviting.catch(() => { });
213
+ if (call.ticket)
214
+ await this.respond(call, CallActionEnd);
215
+ }
216
+ async microphone(enabled) {
217
+ const connection = this.connection;
218
+ if (!connection)
219
+ return;
220
+ await connection.microphone(enabled);
221
+ if (connection === this.connection)
222
+ this.publish({ microphone: enabled });
223
+ }
224
+ async camera(enabled) {
225
+ const connection = this.connection;
226
+ if (!connection || this.state.call?.mode !== CallModeVideo)
227
+ return;
228
+ await connection.camera(enabled);
229
+ if (connection === this.connection)
230
+ this.publish({ camera: enabled });
231
+ }
232
+ dispose() {
233
+ void this.end().catch(this.opts.on_error);
234
+ this.disposed = true;
235
+ this.closed.clear();
236
+ }
237
+ begin(call, phase) {
238
+ this.controller = new AbortController();
239
+ this.had_remote = false;
240
+ this.state = {
241
+ ...idleCallState(),
242
+ call,
243
+ phase,
244
+ camera: call.mode === CallModeVideo,
245
+ };
246
+ this.opts.on_change(this.state);
247
+ }
248
+ async connect(call, token) {
249
+ const signal = this.controller.signal;
250
+ if (!this.current(call))
251
+ return;
252
+ this.connecting = call.id;
253
+ let connection;
254
+ try {
255
+ connection = await this.opts.media.connect({
256
+ token,
257
+ call,
258
+ room_id: call.room_id,
259
+ video: call.mode === CallModeVideo,
260
+ signal,
261
+ on_change: (state) => {
262
+ if (!this.current(call))
263
+ return;
264
+ const remote = state.participants.some((participant) => !participant.local);
265
+ if (remote) {
266
+ this.had_remote = true;
267
+ this.clearTimer();
268
+ }
269
+ else if (this.had_remote && !state.reconnecting) {
270
+ void this.end().catch(this.opts.on_error);
271
+ return;
272
+ }
273
+ const local = state.participants.find((participant) => participant.local);
274
+ this.publish({
275
+ participants: state.participants,
276
+ ...(local ? { microphone: local.audio, camera: local.video } : {}),
277
+ phase: state.reconnecting
278
+ ? "reconnecting"
279
+ : this.had_remote
280
+ ? "connected"
281
+ : this.state.phase,
282
+ });
283
+ },
284
+ on_disconnect: (error) => {
285
+ if (!this.current(call))
286
+ return;
287
+ void this.end().catch(this.opts.on_error);
288
+ if (error)
289
+ this.opts.on_error(error);
290
+ },
291
+ });
292
+ }
293
+ finally {
294
+ if (this.connecting === call.id)
295
+ this.connecting = "";
296
+ }
297
+ if (!this.current(call))
298
+ connection.disconnect();
299
+ else
300
+ this.connection = connection;
301
+ }
302
+ access(value) {
303
+ if (!value?.ticket ||
304
+ !value.call_id ||
305
+ !value.room_id ||
306
+ value.owner_id !== this.opts.owner_id ||
307
+ value.state === CallStateEnded)
308
+ throw errResolveFailed({
309
+ resource: "call",
310
+ msg: "This call is no longer available.",
311
+ });
312
+ return value;
313
+ }
314
+ async respond(call, action) {
315
+ const out = await this.opts.calls.respondCallSession({
316
+ ticket: call.ticket,
317
+ device_id: this.opts.device_id,
318
+ action,
319
+ });
320
+ if (action === CallActionEnd && out.value)
321
+ return out.value;
322
+ return this.access(out.value);
323
+ }
324
+ current(call) {
325
+ return (!this.disposed &&
326
+ this.state.call === call &&
327
+ !this.controller?.signal.aborted);
328
+ }
329
+ publish(patch) {
330
+ this.state = { ...this.state, ...patch };
331
+ this.opts.on_change(this.state);
332
+ }
333
+ reset(call) {
334
+ this.remember(call.id);
335
+ this.clearTimer();
336
+ this.state = idleCallState();
337
+ this.controller?.abort();
338
+ this.controller = undefined;
339
+ const connection = this.connection;
340
+ this.connection = undefined;
341
+ connection?.disconnect();
342
+ this.recipients = [];
343
+ this.opts.on_change(this.state);
344
+ }
345
+ remember(id) {
346
+ this.closed.add(id);
347
+ if (this.closed.size > closedCallLimit)
348
+ this.closed.delete(this.closed.values().next().value);
349
+ }
350
+ armTimeout(call) {
351
+ this.clearTimer();
352
+ if (this.had_remote)
353
+ return;
354
+ this.timer = setTimeout(() => {
355
+ if (this.current(call))
356
+ void this.end().catch(this.opts.on_error);
357
+ }, Math.max(0, call.expires_at - Date.now()));
358
+ }
359
+ clearTimer() {
360
+ if (this.timer)
361
+ clearTimeout(this.timer);
362
+ this.timer = undefined;
363
+ }
364
+ }
@@ -1,6 +1,7 @@
1
1
  export * from "./auth/auth.js";
2
2
  export * from "./billable/billable.js";
3
3
  export * from "./calls/calls.js";
4
+ export * from "./calls/session.js";
4
5
  export * from "./chat/chat.js";
5
6
  export * from "./chat/data.js";
6
7
  export * from "./chat/forms.js";
package/dist/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export * from "./auth/auth.js";
2
2
  export * from "./billable/billable.js";
3
3
  export * from "./calls/calls.js";
4
+ export * from "./calls/session.js";
4
5
  export * from "./chat/chat.js";
5
6
  export * from "./chat/data.js";
6
7
  export * from "./chat/forms.js";
@@ -7,6 +7,9 @@ export type NotificationsFXOptions = {
7
7
  export type SyncDeviceTokenOptions = {
8
8
  owner_id: string;
9
9
  previous_id?: string;
10
+ token?: string;
11
+ transport?: string;
12
+ sandbox?: boolean;
10
13
  };
11
14
  export type UnregisterDeviceTokenOptions = {
12
15
  id: string;
@@ -3,7 +3,7 @@
3
3
  // Licensed under the Apache License, Version 2.0 (the "License"); you may
4
4
  // not use this file except in compliance with the License. You may obtain
5
5
  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
- import { ZeroID } from "@fabriktor/schema";
6
+ import { ZeroID, PushTransportFCM } from "@fabriktor/schema";
7
7
  import { errRequired } from "../core/err.js";
8
8
  import { requiredOperationID, resolvedID } from "../core/id.js";
9
9
  const msgOwnerIDRequired = "Owner ID is required.";
@@ -25,7 +25,7 @@ export class NotificationsFX {
25
25
  msg: msgOwnerIDRequired,
26
26
  });
27
27
  }
28
- const token = (await this.getDeviceToken()).trim();
28
+ const token = (opts.token ?? (await this.getDeviceToken())).trim();
29
29
  if (token === "") {
30
30
  throw errRequired({
31
31
  field: "token",
@@ -35,6 +35,8 @@ export class NotificationsFX {
35
35
  const input = {
36
36
  in: {
37
37
  token,
38
+ transport: opts.transport ?? PushTransportFCM,
39
+ sandbox: opts.sandbox ?? false,
38
40
  },
39
41
  query: {
40
42
  owner_id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.166",
3
+ "version": "0.0.168",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,9 +17,9 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.102",
20
+ "@fabriktor/client": "0.0.103",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.74",
22
+ "@fabriktor/schema": "0.0.75",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }