effect-cloudflare-webrtc 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +439 -2
- package/dist/AudioSink-BybkMP2y.d.ts +54 -0
- package/dist/Readable-CJPSx6Uq.js +65 -0
- package/dist/Readable-CJPSx6Uq.js.map +1 -0
- package/dist/Realtime-B5OIHlLR.d.ts +129 -0
- package/dist/Realtime-B6TjV8su.js +195 -0
- package/dist/Realtime-B6TjV8su.js.map +1 -0
- package/dist/RealtimeClient-Bl0Tun5r.js +2488 -0
- package/dist/RealtimeClient-Bl0Tun5r.js.map +1 -0
- package/dist/RealtimeClient-ESFO5vfF.d.ts +412 -0
- package/dist/RealtimeClient-K7oKgsB9.d.ts +1000 -0
- package/dist/chunk-pbuEa-1d.js +13 -0
- package/dist/client/index.d.ts +275 -0
- package/dist/client/index.js +493 -0
- package/dist/client/index.js.map +1 -0
- package/dist/effect/client/index.d.ts +434 -0
- package/dist/effect/client/index.js +2 -0
- package/dist/effect/server/index.d.ts +2 -0
- package/dist/effect/server/index.js +2 -0
- package/dist/react/index.d.ts +44 -0
- package/dist/react/index.js +107 -0
- package/dist/react/index.js.map +1 -0
- package/dist/server/index.d.ts +23 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/package.json +92 -4
|
@@ -0,0 +1,493 @@
|
|
|
1
|
+
import { b as microtaskScheduler, d as MediaSources, f as MicrophoneSource, l as ScreenShareSource, t as RealtimeClient, u as CameraSource, v as DevicePreferences, x as MediaDevices, y as AudioSink } from "../RealtimeClient-Bl0Tun5r.js";
|
|
2
|
+
import { n as isReadable, r as writable, t as Store } from "../Readable-CJPSx6Uq.js";
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Exit from "effect/Exit";
|
|
5
|
+
import * as Layer from "effect/Layer";
|
|
6
|
+
import * as ManagedRuntime from "effect/ManagedRuntime";
|
|
7
|
+
import * as Scope from "effect/Scope";
|
|
8
|
+
import * as Stream from "effect/Stream";
|
|
9
|
+
import * as Fiber from "effect/Fiber";
|
|
10
|
+
import * as Scheduler from "effect/Scheduler";
|
|
11
|
+
import * as Duration from "effect/Duration";
|
|
12
|
+
import * as Queue from "effect/Queue";
|
|
13
|
+
import * as Cause from "effect/Cause";
|
|
14
|
+
import * as Logger from "effect/Logger";
|
|
15
|
+
import * as References from "effect/References";
|
|
16
|
+
import * as Schedule from "effect/Schedule";
|
|
17
|
+
//#region src/client/logging.ts
|
|
18
|
+
const order = [
|
|
19
|
+
"none",
|
|
20
|
+
"error",
|
|
21
|
+
"warn",
|
|
22
|
+
"info",
|
|
23
|
+
"debug"
|
|
24
|
+
];
|
|
25
|
+
let globalLevel = "warn";
|
|
26
|
+
/**
|
|
27
|
+
* Sets the log level of the media sources (`createMicrophoneSource` and the others) and of
|
|
28
|
+
* each client that has no `logLevel` option. Default: "warn".
|
|
29
|
+
*/
|
|
30
|
+
function setLogLevel(level) {
|
|
31
|
+
globalLevel = level;
|
|
32
|
+
}
|
|
33
|
+
const toConsole = (entry) => {
|
|
34
|
+
console[entry.level]("[effect-cloudflare-webrtc]", ...entry.message);
|
|
35
|
+
};
|
|
36
|
+
/** Sends the logs of the Effect core to the console or to a function. */
|
|
37
|
+
const loggerLayer = (options) => {
|
|
38
|
+
const write = options.logger ?? toConsole;
|
|
39
|
+
const logger = Logger.make(({ logLevel, message, date }) => {
|
|
40
|
+
const level = logLevel === "Fatal" || logLevel === "Error" ? "error" : logLevel === "Warn" ? "warn" : logLevel === "Info" ? "info" : "debug";
|
|
41
|
+
const limit = options.logLevel ?? globalLevel;
|
|
42
|
+
if (order.indexOf(level) > order.indexOf(limit)) return;
|
|
43
|
+
write({
|
|
44
|
+
level,
|
|
45
|
+
message: Array.isArray(message) ? message : [message],
|
|
46
|
+
date
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
return Layer.merge(Logger.layer([logger]), Layer.succeed(References.MinimumLogLevel, "All"));
|
|
50
|
+
};
|
|
51
|
+
//#endregion
|
|
52
|
+
//#region src/client/internal.ts
|
|
53
|
+
/** The logger and the scheduler of an internal runtime. */
|
|
54
|
+
const runtimeServices = (logging) => Layer.merge(loggerLayer(logging), Layer.succeed(Scheduler.Scheduler, microtaskScheduler));
|
|
55
|
+
/** Runs the effect. The promise rejects with the error of the effect. */
|
|
56
|
+
const settle = (runtime, effect) => runtime.runPromiseExit(effect).then((exit) => {
|
|
57
|
+
if (Exit.isSuccess(exit)) return exit.value;
|
|
58
|
+
throw Cause.squash(exit.cause);
|
|
59
|
+
});
|
|
60
|
+
/** Calls the function with each value. Returns a function that stops it. */
|
|
61
|
+
const forward = (runtime, stream, f) => {
|
|
62
|
+
const fiber = runtime.runFork(Stream.runForEach(stream, (value) => Effect.sync(() => f(value))));
|
|
63
|
+
return () => {
|
|
64
|
+
runtime.runFork(Fiber.interrupt(fiber));
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
/** The defined values of the `Readable`, while the stream has a consumer. */
|
|
68
|
+
const streamOf = (readable) => Stream.callback((queue) => Effect.acquireRelease(Effect.sync(() => readable.subscribe((value) => {
|
|
69
|
+
if (value !== void 0) Queue.offerUnsafe(queue, value);
|
|
70
|
+
})), (unsubscribe) => Effect.sync(unsubscribe)));
|
|
71
|
+
//#endregion
|
|
72
|
+
//#region src/client/sources.ts
|
|
73
|
+
/**
|
|
74
|
+
* A handle of the Effect core that is made at the first use. The module
|
|
75
|
+
* and the source functions can thus be used where there is no browser.
|
|
76
|
+
*/
|
|
77
|
+
var Lazy = class {
|
|
78
|
+
/** The handle, after it is made. */
|
|
79
|
+
ready;
|
|
80
|
+
started;
|
|
81
|
+
scope;
|
|
82
|
+
disposed = false;
|
|
83
|
+
wires = [];
|
|
84
|
+
stops = [];
|
|
85
|
+
constructor(runtime, make) {
|
|
86
|
+
this.runtime = runtime;
|
|
87
|
+
this.make = make;
|
|
88
|
+
}
|
|
89
|
+
ensure = () => {
|
|
90
|
+
this.started ??= this.runtime().runPromise(Effect.gen({ self: this }, function* () {
|
|
91
|
+
const scope = yield* Scope.make();
|
|
92
|
+
this.scope = scope;
|
|
93
|
+
return yield* this.make.pipe(Scope.provide(scope));
|
|
94
|
+
})).then((handle) => {
|
|
95
|
+
if (!this.disposed) {
|
|
96
|
+
this.ready = handle;
|
|
97
|
+
this.stops = this.wires.map((wire) => wire(handle));
|
|
98
|
+
}
|
|
99
|
+
return handle;
|
|
100
|
+
});
|
|
101
|
+
return this.started;
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Runs a command that only changes a state. After the handle is made,
|
|
105
|
+
* the command runs synchronously, inside the event that called it, so
|
|
106
|
+
* that the browser sees the user gesture.
|
|
107
|
+
*/
|
|
108
|
+
command = (effect) => {
|
|
109
|
+
if (this.disposed) return;
|
|
110
|
+
if (this.ready !== void 0) this.runtime().runSync(effect(this.ready));
|
|
111
|
+
else this.ensure().then((handle) => {
|
|
112
|
+
if (!this.disposed) this.runtime().runSync(effect(handle));
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
/** Calls the listener with each value of the stream of the handle. */
|
|
116
|
+
listen = (stream, listener) => {
|
|
117
|
+
let stop;
|
|
118
|
+
let stopped = false;
|
|
119
|
+
this.ensure().then((handle) => {
|
|
120
|
+
if (!stopped) stop = forward(this.runtime(), stream(handle), listener);
|
|
121
|
+
});
|
|
122
|
+
return () => {
|
|
123
|
+
stopped = true;
|
|
124
|
+
stop?.();
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
/**
|
|
128
|
+
* A value of the handle. The first subscriber of one of the values makes
|
|
129
|
+
* the handle. Before that, the value is the initial value.
|
|
130
|
+
*/
|
|
131
|
+
state = (initial, subscribable) => {
|
|
132
|
+
const store = new Store(initial, { onActive: () => {
|
|
133
|
+
this.ensure();
|
|
134
|
+
return () => {};
|
|
135
|
+
} });
|
|
136
|
+
this.wires.push((handle) => forward(this.runtime(), subscribable(handle).changes, store.set));
|
|
137
|
+
return store;
|
|
138
|
+
};
|
|
139
|
+
/** A track of the handle. It is `undefined` with no subscriber. */
|
|
140
|
+
track = (stream) => {
|
|
141
|
+
const store = new Store(void 0, { onActive: () => {
|
|
142
|
+
const stop = this.listen(stream, store.set);
|
|
143
|
+
return () => {
|
|
144
|
+
stop();
|
|
145
|
+
store.set(void 0);
|
|
146
|
+
};
|
|
147
|
+
} });
|
|
148
|
+
return store;
|
|
149
|
+
};
|
|
150
|
+
async run(f) {
|
|
151
|
+
const h = this.ready ?? await this.ensure();
|
|
152
|
+
if (this.disposed) throw new Error("Source disposed");
|
|
153
|
+
return this.runtime().runPromise(f(h));
|
|
154
|
+
}
|
|
155
|
+
dispose = async () => {
|
|
156
|
+
this.disposed = true;
|
|
157
|
+
this.ready = void 0;
|
|
158
|
+
for (const stop of this.stops.splice(0)) stop();
|
|
159
|
+
if (this.started === void 0) return;
|
|
160
|
+
await this.started;
|
|
161
|
+
if (this.scope !== void 0) await this.runtime().runPromise(Scope.close(this.scope, Exit.void));
|
|
162
|
+
};
|
|
163
|
+
/**
|
|
164
|
+
* A child scope of the scope of the handle. `dispose()` closes it. It is
|
|
165
|
+
* `undefined` after `dispose`.
|
|
166
|
+
*/
|
|
167
|
+
childScope = async () => {
|
|
168
|
+
if (this.disposed) return void 0;
|
|
169
|
+
await this.ensure();
|
|
170
|
+
if (this.disposed || this.scope === void 0) return void 0;
|
|
171
|
+
return Scope.forkUnsafe(this.scope);
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
const toCoreTransform = (transform) => (track) => Effect.gen(function* () {
|
|
175
|
+
const controller = yield* Effect.acquireRelease(Effect.sync(() => new AbortController()), (made) => Effect.sync(() => made.abort()));
|
|
176
|
+
return yield* Effect.tryPromise(async () => transform(track, { signal: controller.signal }));
|
|
177
|
+
});
|
|
178
|
+
/** The part of a broadcast track that has no source flag. */
|
|
179
|
+
const plainTrack = (lazy, pick) => ({
|
|
180
|
+
broadcastTrack: lazy.track((handle) => pick(handle).broadcastTrack),
|
|
181
|
+
localMonitorTrack: lazy.track((handle) => pick(handle).localMonitorTrack),
|
|
182
|
+
isBroadcasting: lazy.state(false, (handle) => pick(handle).isBroadcasting),
|
|
183
|
+
stopBroadcasting: () => lazy.command((handle) => pick(handle).stopBroadcasting),
|
|
184
|
+
onError: (listener) => lazy.listen((handle) => pick(handle).errors, listener),
|
|
185
|
+
addTransform: (transform) => {
|
|
186
|
+
const added = lazy.childScope().then((scope) => {
|
|
187
|
+
const handle = lazy.ready;
|
|
188
|
+
if (scope === void 0 || handle === void 0) return void 0;
|
|
189
|
+
return lazy.runtime().runPromise(Effect.gen(function* () {
|
|
190
|
+
yield* pick(handle).addTransform(toCoreTransform(transform)).pipe(Scope.provide(scope));
|
|
191
|
+
return scope;
|
|
192
|
+
}));
|
|
193
|
+
});
|
|
194
|
+
return () => {
|
|
195
|
+
added.then((scope) => {
|
|
196
|
+
if (scope !== void 0) lazy.runtime().runPromise(Scope.close(scope, Exit.void));
|
|
197
|
+
});
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
const plainDevice = (runtime, make) => (options = {}) => {
|
|
202
|
+
const lazy = new Lazy(runtime, make({
|
|
203
|
+
...options,
|
|
204
|
+
transforms: options.transforms?.map(toCoreTransform)
|
|
205
|
+
}));
|
|
206
|
+
return wrapDevice(lazy, (h) => h, lazy.dispose);
|
|
207
|
+
};
|
|
208
|
+
function wrapDevice(lazy, pick, dispose) {
|
|
209
|
+
const permission = lazy.state("unknown", (handle) => pick(handle).permissionState);
|
|
210
|
+
return {
|
|
211
|
+
...plainTrack(lazy, pick),
|
|
212
|
+
startBroadcasting: () => lazy.run((h) => pick(h).startBroadcasting),
|
|
213
|
+
toggleBroadcasting: () => lazy.run((h) => pick(h).toggleBroadcasting),
|
|
214
|
+
isAcquiring: lazy.state(false, (h) => pick(h).isAcquiring),
|
|
215
|
+
isAcquired: lazy.state(false, (h) => pick(h).isAcquired),
|
|
216
|
+
acquire: () => lazy.run((h) => pick(h).acquire),
|
|
217
|
+
release: () => lazy.run((h) => pick(h).release),
|
|
218
|
+
permissionState: permission,
|
|
219
|
+
availableDevices: lazy.state([], (handle) => pick(handle).availableDevices),
|
|
220
|
+
activeDevice: lazy.state(void 0, (handle) => pick(handle).activeDevice),
|
|
221
|
+
setPreferredDevice: (device) => lazy.command((handle) => pick(handle).setPreferredDevice(device)),
|
|
222
|
+
onDeviceFailure: (listener) => lazy.listen((handle) => pick(handle).deviceFailures, listener),
|
|
223
|
+
dispose
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* The media sources of the plain API on an internal runtime. Tests supply
|
|
228
|
+
* the runtime and the fallback tracks, because the default fallback tracks
|
|
229
|
+
* need a browser.
|
|
230
|
+
*/
|
|
231
|
+
function makeSources(runtime, fallbackTracks = {}) {
|
|
232
|
+
return {
|
|
233
|
+
/** Acquire both idle devices in one request or control either device independently. Dispose the pair when finished. */
|
|
234
|
+
createMediaSources: (options = {}) => {
|
|
235
|
+
const convert = (o) => ({
|
|
236
|
+
...o,
|
|
237
|
+
transforms: o?.transforms?.map(toCoreTransform)
|
|
238
|
+
});
|
|
239
|
+
const lazy = new Lazy(runtime, MediaSources.make({
|
|
240
|
+
microphone: {
|
|
241
|
+
...convert(options.microphone),
|
|
242
|
+
fallbackTrack: fallbackTracks.audio
|
|
243
|
+
},
|
|
244
|
+
camera: {
|
|
245
|
+
...convert(options.camera),
|
|
246
|
+
fallbackTrack: fallbackTracks.video
|
|
247
|
+
}
|
|
248
|
+
}));
|
|
249
|
+
return {
|
|
250
|
+
microphone: wrapDevice(lazy, (h) => h.microphone, () => lazy.run((h) => h.microphone.release)),
|
|
251
|
+
camera: wrapDevice(lazy, (h) => h.camera, () => lazy.run((h) => h.camera.release)),
|
|
252
|
+
acquire: () => lazy.run((h) => h.acquire),
|
|
253
|
+
release: () => lazy.run((h) => h.release),
|
|
254
|
+
dispose: lazy.dispose
|
|
255
|
+
};
|
|
256
|
+
},
|
|
257
|
+
/** The microphone: device selection, resilient acquisition, mute. */
|
|
258
|
+
createMicrophoneSource: plainDevice(runtime, (options) => MicrophoneSource.make({
|
|
259
|
+
...options,
|
|
260
|
+
fallbackTrack: fallbackTracks.audio
|
|
261
|
+
})),
|
|
262
|
+
/** The camera: device selection, resilient acquisition, on and off. */
|
|
263
|
+
createCameraSource: plainDevice(runtime, (options) => CameraSource.make({
|
|
264
|
+
...options,
|
|
265
|
+
fallbackTrack: fallbackTracks.video
|
|
266
|
+
})),
|
|
267
|
+
/** A screen share: an audio and a video track from one browser prompt. */
|
|
268
|
+
createScreenShareSource: (options = {}) => {
|
|
269
|
+
const lazy = new Lazy(runtime, ScreenShareSource.make({
|
|
270
|
+
...options,
|
|
271
|
+
fallbackTracks
|
|
272
|
+
}));
|
|
273
|
+
const track = (pick) => ({
|
|
274
|
+
...plainTrack(lazy, pick),
|
|
275
|
+
startBroadcasting: () => lazy.command((h) => pick(h).startBroadcasting),
|
|
276
|
+
toggleBroadcasting: () => lazy.command((h) => pick(h).toggleBroadcasting)
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
audio: track((handle) => handle.audio),
|
|
280
|
+
video: track((handle) => handle.video),
|
|
281
|
+
isEnabled: lazy.state(options.enabled ?? false, (handle) => handle.isEnabled),
|
|
282
|
+
isBroadcasting: lazy.state(false, (handle) => handle.isBroadcasting),
|
|
283
|
+
enable: () => lazy.command((handle) => handle.enable),
|
|
284
|
+
disable: () => lazy.command((handle) => handle.disable),
|
|
285
|
+
toggleEnabled: () => lazy.command((handle) => handle.toggleEnabled),
|
|
286
|
+
startBroadcasting: () => lazy.command((handle) => handle.startBroadcasting),
|
|
287
|
+
stopBroadcasting: () => lazy.command((handle) => handle.stopBroadcasting),
|
|
288
|
+
toggleBroadcasting: () => lazy.command((handle) => handle.toggleBroadcasting),
|
|
289
|
+
dispose: lazy.dispose
|
|
290
|
+
};
|
|
291
|
+
},
|
|
292
|
+
/** Plays pulled audio tracks in one `<audio>` element. */
|
|
293
|
+
createAudioSink: (options) => {
|
|
294
|
+
const lazy = new Lazy(runtime, AudioSink.make(options));
|
|
295
|
+
lazy.ensure();
|
|
296
|
+
return {
|
|
297
|
+
attach: (track) => {
|
|
298
|
+
const attached = lazy.childScope().then((scope) => {
|
|
299
|
+
const handle = lazy.ready;
|
|
300
|
+
if (scope === void 0 || handle === void 0) return void 0;
|
|
301
|
+
return lazy.runtime().runPromise(Effect.gen(function* () {
|
|
302
|
+
yield* handle.attach(streamOf(track)).pipe(Scope.provide(scope));
|
|
303
|
+
return scope;
|
|
304
|
+
}));
|
|
305
|
+
});
|
|
306
|
+
return () => {
|
|
307
|
+
attached.then((scope) => {
|
|
308
|
+
if (scope !== void 0) lazy.runtime().runPromise(Scope.close(scope, Exit.void));
|
|
309
|
+
});
|
|
310
|
+
};
|
|
311
|
+
},
|
|
312
|
+
isSinkIdSupported: options.audioElement.setSinkId !== void 0,
|
|
313
|
+
setSinkId: (sinkId) => lazy.ensure().then((handle) => settle(lazy.runtime(), handle.setSinkId(sinkId))),
|
|
314
|
+
availableDevices: lazy.state([], (handle) => handle.availableDevices),
|
|
315
|
+
isPlaying: lazy.state(false, (handle) => handle.isPlaying),
|
|
316
|
+
dispose: lazy.dispose
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
let shared;
|
|
322
|
+
/** One runtime for all media sources of the page. Made at the first use. */
|
|
323
|
+
const browserSourcesRuntime = () => {
|
|
324
|
+
shared ??= ManagedRuntime.make(Layer.provideMerge(Layer.mergeAll(MediaDevices.layerBrowser, DevicePreferences.layerLocalStorage), runtimeServices({})));
|
|
325
|
+
return shared;
|
|
326
|
+
};
|
|
327
|
+
//#endregion
|
|
328
|
+
//#region src/client/RealtimeClient.ts
|
|
329
|
+
function retrySchedule(retry) {
|
|
330
|
+
const maxDelay = Duration.millis(retry.maxDelay ?? 1e4);
|
|
331
|
+
const delays = Schedule.exponential(Duration.millis(retry.initialDelay ?? 250), retry.factor ?? 2).pipe(Schedule.modifyDelay(({ duration }) => Effect.succeed(Duration.min(duration, maxDelay))));
|
|
332
|
+
return retry.maxAttempts === void 0 ? delays : Schedule.max([delays, Schedule.recurs(retry.maxAttempts)]);
|
|
333
|
+
}
|
|
334
|
+
const toConfig = (options) => {
|
|
335
|
+
const schedule = options.retry === void 0 ? void 0 : retrySchedule(options.retry);
|
|
336
|
+
return {
|
|
337
|
+
prefix: options.prefix,
|
|
338
|
+
apiExtraParams: options.apiExtraParams,
|
|
339
|
+
headers: options.headers,
|
|
340
|
+
iceServers: options.iceServers,
|
|
341
|
+
maxApiHistory: options.maxApiHistory,
|
|
342
|
+
tracePropagation: options.tracePropagation,
|
|
343
|
+
sessionRetry: schedule,
|
|
344
|
+
trackRetry: schedule
|
|
345
|
+
};
|
|
346
|
+
};
|
|
347
|
+
/** Pushes local tracks to the Realtime SFU and pulls remote tracks from it. */
|
|
348
|
+
function createRealtimeClient(options = {}) {
|
|
349
|
+
return createRealtimeFromLayer(options, RealtimeClient.layerBrowser({
|
|
350
|
+
...toConfig(options),
|
|
351
|
+
credentials: options.credentials
|
|
352
|
+
}));
|
|
353
|
+
}
|
|
354
|
+
/** `createRealtimeClient` on a different layer of the core. Tests use it. */
|
|
355
|
+
function createRealtimeFromLayer(options, layer) {
|
|
356
|
+
const runtime = ManagedRuntime.make(Layer.provideMerge(layer, runtimeServices(options)));
|
|
357
|
+
const core = runtime.runPromise(Effect.gen(function* () {
|
|
358
|
+
return yield* RealtimeClient;
|
|
359
|
+
}));
|
|
360
|
+
/** Runs when the core is ready. Returns a function that stops it. */
|
|
361
|
+
const whenReady = (start) => {
|
|
362
|
+
let stop;
|
|
363
|
+
let stopped = false;
|
|
364
|
+
core.then((service) => {
|
|
365
|
+
if (!stopped) stop = start(service);
|
|
366
|
+
});
|
|
367
|
+
return () => {
|
|
368
|
+
stopped = true;
|
|
369
|
+
stop?.();
|
|
370
|
+
};
|
|
371
|
+
};
|
|
372
|
+
const session = new Store({ _tag: "Idle" });
|
|
373
|
+
whenReady((service) => forward(runtime, service.sessionState.changes, session.set));
|
|
374
|
+
const maxHistory = Math.max(1, options.maxApiHistory ?? 100);
|
|
375
|
+
const history = [];
|
|
376
|
+
let loggedAuthRedirect = false;
|
|
377
|
+
whenReady((service) => forward(runtime, service.apiEvents, (entry) => {
|
|
378
|
+
history.push(entry);
|
|
379
|
+
if (history.length > maxHistory) history.shift();
|
|
380
|
+
if (entry.type !== "response") return;
|
|
381
|
+
if (entry.status !== 0) {
|
|
382
|
+
loggedAuthRedirect = false;
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (options.onAuthRedirect !== void 0) options.onAuthRedirect();
|
|
386
|
+
else if (!loggedAuthRedirect) {
|
|
387
|
+
loggedAuthRedirect = true;
|
|
388
|
+
runtime.runFork(Effect.logError("The request was redirected and no onAuthRedirect handler is set").pipe(Effect.annotateLogs({ endpoint: entry.endpoint })));
|
|
389
|
+
}
|
|
390
|
+
}));
|
|
391
|
+
/** The handles that are open. `dispose` closes them. */
|
|
392
|
+
const open = /* @__PURE__ */ new Set();
|
|
393
|
+
/**
|
|
394
|
+
* Starts a push or a pull in its own scope. `close` waits for the start,
|
|
395
|
+
* so that a close immediately after the start is safe.
|
|
396
|
+
*/
|
|
397
|
+
const start = (make, onClosed) => {
|
|
398
|
+
let closing;
|
|
399
|
+
const started = core.then((service) => runtime.runPromise(Effect.gen(function* () {
|
|
400
|
+
const scope = yield* Scope.make();
|
|
401
|
+
return {
|
|
402
|
+
scope,
|
|
403
|
+
handle: yield* make(service, scope)
|
|
404
|
+
};
|
|
405
|
+
})));
|
|
406
|
+
const close = () => {
|
|
407
|
+
closing ??= started.then(({ scope }) => runtime.runPromise(Scope.close(scope, Exit.void))).then(() => {
|
|
408
|
+
open.delete(close);
|
|
409
|
+
onClosed();
|
|
410
|
+
});
|
|
411
|
+
return closing;
|
|
412
|
+
};
|
|
413
|
+
open.add(close);
|
|
414
|
+
return {
|
|
415
|
+
handle: started.then(({ handle }) => handle),
|
|
416
|
+
close
|
|
417
|
+
};
|
|
418
|
+
};
|
|
419
|
+
const realtime = {
|
|
420
|
+
sessionState: session,
|
|
421
|
+
push: (source, pushOptions = {}) => {
|
|
422
|
+
const trackName = pushOptions.trackName ?? crypto.randomUUID();
|
|
423
|
+
const state = new Store({ _tag: "WaitingForTrack" });
|
|
424
|
+
const metadata = new Store(void 0);
|
|
425
|
+
const setState = (next) => {
|
|
426
|
+
metadata.set(next._tag === "Published" ? next.metadata : void 0);
|
|
427
|
+
state.set(next);
|
|
428
|
+
};
|
|
429
|
+
const { handle, close } = start((service, scope) => Effect.gen(function* () {
|
|
430
|
+
const pushed = yield* service.push(isReadable(source) ? streamOf(source) : Stream.make(source), {
|
|
431
|
+
sendEncodings: pushOptions.sendEncodings,
|
|
432
|
+
trackName
|
|
433
|
+
});
|
|
434
|
+
yield* pushed.state.changes.pipe(Stream.runForEach((next) => Effect.sync(() => setState(next))), Effect.forkScoped);
|
|
435
|
+
return pushed;
|
|
436
|
+
}).pipe(Scope.provide(scope)), () => setState({ _tag: "Closed" }));
|
|
437
|
+
return {
|
|
438
|
+
trackName,
|
|
439
|
+
state,
|
|
440
|
+
metadata,
|
|
441
|
+
setSendEncodings: (encodings) => handle.then((pushed) => settle(runtime, pushed.setSendEncodings(encodings).pipe(Effect.tapError((error) => Effect.logWarning("setSendEncodings failed", error))))),
|
|
442
|
+
close,
|
|
443
|
+
[Symbol.asyncDispose]: close
|
|
444
|
+
};
|
|
445
|
+
},
|
|
446
|
+
pull: (target, pullOptions = {}) => {
|
|
447
|
+
const state = new Store({ _tag: "WaitingForMetadata" });
|
|
448
|
+
const track = new Store(void 0);
|
|
449
|
+
const setState = (next) => {
|
|
450
|
+
track.set(next._tag === "Live" ? next.track : void 0);
|
|
451
|
+
state.set(next);
|
|
452
|
+
};
|
|
453
|
+
const { handle, close } = start((service, scope) => Effect.gen(function* () {
|
|
454
|
+
const pulled = yield* service.pull(isReadable(target) ? streamOf(target) : target, pullOptions);
|
|
455
|
+
yield* pulled.state.changes.pipe(Stream.runForEach((next) => Effect.sync(() => setState(next))), Effect.forkScoped);
|
|
456
|
+
return pulled;
|
|
457
|
+
}).pipe(Scope.provide(scope)), () => setState({ _tag: "Closed" }));
|
|
458
|
+
return {
|
|
459
|
+
state,
|
|
460
|
+
track,
|
|
461
|
+
setPreferredRid: (rid) => handle.then((pulled) => settle(runtime, pulled.setPreferredRid(rid).pipe(Effect.tapError((error) => Effect.logWarning("setPreferredRid failed", error))))),
|
|
462
|
+
close,
|
|
463
|
+
[Symbol.asyncDispose]: close
|
|
464
|
+
};
|
|
465
|
+
},
|
|
466
|
+
onTransceiver: (listener) => whenReady((service) => forward(runtime, service.transceivers, listener)),
|
|
467
|
+
onStats: (listener, statsOptions = {}) => whenReady((service) => forward(runtime, service.stats(statsOptions.interval === void 0 ? {} : { interval: Duration.millis(statsOptions.interval) }), listener)),
|
|
468
|
+
onApiEvent: (listener) => whenReady((service) => forward(runtime, service.apiEvents, listener)),
|
|
469
|
+
getApiHistory: () => [...history],
|
|
470
|
+
dispose: async () => {
|
|
471
|
+
await Promise.all([...open].map((close) => close()));
|
|
472
|
+
await runtime.dispose();
|
|
473
|
+
},
|
|
474
|
+
[Symbol.asyncDispose]: () => realtime.dispose()
|
|
475
|
+
};
|
|
476
|
+
return realtime;
|
|
477
|
+
}
|
|
478
|
+
//#endregion
|
|
479
|
+
//#region src/client/index.ts
|
|
480
|
+
const sources = makeSources(browserSourcesRuntime);
|
|
481
|
+
/** The microphone: device selection, resilient acquisition, mute. */
|
|
482
|
+
const createMicrophoneSource = sources.createMicrophoneSource;
|
|
483
|
+
/** The camera: device selection, resilient acquisition, on and off. */
|
|
484
|
+
const createCameraSource = sources.createCameraSource;
|
|
485
|
+
/** A screen share: an audio and a video track from one browser prompt. */
|
|
486
|
+
const createScreenShareSource = sources.createScreenShareSource;
|
|
487
|
+
/** Plays pulled audio tracks in one `<audio>` element. */
|
|
488
|
+
const createAudioSink = sources.createAudioSink;
|
|
489
|
+
const createMediaSources = sources.createMediaSources;
|
|
490
|
+
//#endregion
|
|
491
|
+
export { createAudioSink, createCameraSource, createMediaSources, createMicrophoneSource, createRealtimeClient, createScreenShareSource, setLogLevel, writable };
|
|
492
|
+
|
|
493
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["CoreScreenShareSource","CoreAudioSink","Core"],"sources":["../../src/client/logging.ts","../../src/client/internal.ts","../../src/client/sources.ts","../../src/client/RealtimeClient.ts","../../src/client/index.ts"],"sourcesContent":["import * as Layer from \"effect/Layer\";\nimport * as Logger from \"effect/Logger\";\nimport * as References from \"effect/References\";\n\nexport type LogLevel = \"none\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\nexport interface LogEntry {\n readonly level: Exclude<LogLevel, \"none\">;\n /** The parts of the message, as for `console.log`. */\n readonly message: ReadonlyArray<unknown>;\n readonly date: Date;\n}\n\nconst order: ReadonlyArray<LogLevel> = [\n \"none\",\n \"error\",\n \"warn\",\n \"info\",\n \"debug\"\n];\n\nlet globalLevel: LogLevel = \"warn\";\n\n/**\n * Sets the log level of the media sources (`createMicrophoneSource` and the others) and of\n * each client that has no `logLevel` option. Default: \"warn\".\n */\nexport function setLogLevel(level: LogLevel): void {\n globalLevel = level;\n}\n\nconst toConsole = (entry: LogEntry) => {\n console[entry.level](\"[effect-cloudflare-webrtc]\", ...entry.message);\n};\n\n/** Sends the logs of the Effect core to the console or to a function. */\nexport const loggerLayer = (options: {\n readonly logLevel?: LogLevel | undefined;\n readonly logger?: ((entry: LogEntry) => void) | undefined;\n}): Layer.Layer<never> => {\n const write = options.logger ?? toConsole;\n const logger = Logger.make<unknown, void>(({ logLevel, message, date }) => {\n const level: LogEntry[\"level\"] =\n logLevel === \"Fatal\" || logLevel === \"Error\"\n ? \"error\"\n : logLevel === \"Warn\"\n ? \"warn\"\n : logLevel === \"Info\"\n ? \"info\"\n : \"debug\";\n const limit = options.logLevel ?? globalLevel;\n if (order.indexOf(level) > order.indexOf(limit)) return;\n write({\n level,\n message: Array.isArray(message) ? message : [message],\n date\n });\n });\n return Layer.merge(\n Logger.layer([logger]),\n // The logger filters. The level can change while the page runs.\n Layer.succeed(References.MinimumLogLevel, \"All\")\n );\n};\n","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport * as Layer from \"effect/Layer\";\nimport * as Queue from \"effect/Queue\";\nimport * as Scheduler from \"effect/Scheduler\";\nimport * as Stream from \"effect/Stream\";\n\nimport { microtaskScheduler } from \"../effect/client/internal/scheduler\";\nimport { loggerLayer } from \"./logging\";\n\nimport type * as ManagedRuntime from \"effect/ManagedRuntime\";\nimport type { LogEntry, LogLevel } from \"./logging\";\nimport type { Readable } from \"./Readable\";\n\n/** The logger and the scheduler of an internal runtime. */\nexport const runtimeServices = (logging: {\n readonly logLevel?: LogLevel | undefined;\n readonly logger?: ((entry: LogEntry) => void) | undefined;\n}): Layer.Layer<never> =>\n Layer.merge(\n loggerLayer(logging),\n // Microtasks keep the browser call near the user gesture that caused it.\n Layer.succeed(Scheduler.Scheduler, microtaskScheduler)\n );\n\n/** Runs the effect. The promise rejects with the error of the effect. */\nexport const settle = <R, A, E>(\n runtime: ManagedRuntime.ManagedRuntime<R, never>,\n effect: Effect.Effect<A, E, R>\n): Promise<A> =>\n runtime.runPromiseExit(effect).then((exit) => {\n if (Exit.isSuccess(exit)) return exit.value;\n throw Cause.squash(exit.cause);\n });\n\n/** Calls the function with each value. Returns a function that stops it. */\nexport const forward = <R, A, E>(\n runtime: ManagedRuntime.ManagedRuntime<R, never>,\n stream: Stream.Stream<A, E, R>,\n f: (value: A) => void\n): (() => void) => {\n const fiber = runtime.runFork(\n Stream.runForEach(stream, (value) => Effect.sync(() => f(value)))\n );\n return () => {\n runtime.runFork(Fiber.interrupt(fiber));\n };\n};\n\n/** The defined values of the `Readable`, while the stream has a consumer. */\nexport const streamOf = <A>(\n readable: Readable<A | undefined>\n): Stream.Stream<A> =>\n Stream.callback<A>((queue) =>\n Effect.acquireRelease(\n Effect.sync(() =>\n readable.subscribe((value) => {\n if (value !== undefined) Queue.offerUnsafe(queue, value);\n })\n ),\n (unsubscribe) => Effect.sync(unsubscribe)\n )\n );\n","import * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Layer from \"effect/Layer\";\nimport * as ManagedRuntime from \"effect/ManagedRuntime\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { AudioSink as CoreAudioSink } from \"../effect/client/AudioSink\";\nimport { DevicePreferences } from \"../effect/client/DevicePreferences\";\nimport {\n CameraSource,\n MediaSources,\n MicrophoneSource\n} from \"../effect/client/DeviceSource\";\nimport { MediaDevices } from \"../effect/client/MediaDevices\";\nimport { ScreenShareSource as CoreScreenShareSource } from \"../effect/client/ScreenShareSource\";\nimport { forward, runtimeServices, settle, streamOf } from \"./internal\";\nimport { Store } from \"./Readable\";\n\nimport type { AudioSinkElement } from \"../effect/client/AudioSink\";\nimport type {\n TrackSource as CoreTrackSource,\n TrackTransform as CoreTransform\n} from \"../effect/client/TrackSource\";\nimport type { DeviceSource as CoreDeviceSource } from \"../effect/client/DeviceSource\";\nimport type { SafePermissionState } from \"../effect/client/MediaDevices\";\nimport type { ScreenShareTrack as CoreScreenShareTrack } from \"../effect/client/ScreenShareSource\";\nimport type { Subscribable } from \"../effect/client/Subscribable\";\nimport type { Readable } from \"./Readable\";\nimport type { SourceError } from \"./types\";\n\ntype SourceServices = MediaDevices | DevicePreferences;\nexport type SourcesRuntime = ManagedRuntime.ManagedRuntime<\n SourceServices,\n never\n>;\n\n/**\n * Makes a new track from the content track, for example a background blur.\n * `signal` aborts when the new track must be released: stop the work and\n * free the resources.\n */\nexport type TrackTransform = (\n track: MediaStreamTrack,\n context: { signal: AbortSignal }\n) => MediaStreamTrack | Promise<MediaStreamTrack>;\n\nexport interface TrackSource {\n /**\n * The track to push. It is the content track while the source is enabled\n * and the broadcast is started, and the fallback track in all other\n * conditions. It is active only while it has a subscriber. With no\n * subscriber, the value is `undefined`.\n */\n readonly broadcastTrack: Readable<MediaStreamTrack | undefined>;\n /**\n * The content track while the source is enabled, also when the broadcast\n * is stopped. It is active only while it has a subscriber.\n */\n readonly localMonitorTrack: Readable<MediaStreamTrack | undefined>;\n /** When false, the content source is not acquired. */\n readonly isEnabled: Readable<boolean>;\n /** True while the content track is in the broadcast track. */\n readonly isBroadcasting: Readable<boolean>;\n enable(): void;\n /** Also stops the broadcast. */\n disable(): void;\n toggleEnabled(): void;\n startBroadcasting(): void;\n stopBroadcasting(): void;\n toggleBroadcasting(): void;\n /** Each error of the content source. An error also disables the source. */\n onError(listener: (error: SourceError) => void): () => void;\n /** Returns a function that removes the transformation. */\n addTransform(transform: TrackTransform): () => void;\n}\n\nexport interface DeviceSourceOptions {\n /** Send the captured track when acquired. Construction stays idle. Default: false. */\n broadcasting?: boolean;\n constraints?: Omit<MediaTrackConstraints, \"deviceId\" | \"groupId\">;\n transforms?: TrackTransform[];\n}\n\nexport interface DeviceSource extends Omit<\n TrackSource,\n | \"enable\"\n | \"disable\"\n | \"toggleEnabled\"\n | \"isEnabled\"\n | \"startBroadcasting\"\n | \"toggleBroadcasting\"\n> {\n /** Acquire this device if necessary and send its track. */\n startBroadcasting(): Promise<void>;\n /** Turning on acquires if needed. Muting keeps the device acquired. */\n toggleBroadcasting(): Promise<void>;\n /** Request the device and wait for the first usable track. */\n acquire(): Promise<void>;\n /** Release capture, preserving the broadcast preference. */\n release(): Promise<void>;\n readonly isAcquiring: Readable<boolean>;\n readonly isAcquired: Readable<boolean>;\n readonly permissionState: Readable<PermissionState | \"unknown\">;\n /** The devices of this kind. Use it for a device selector. */\n readonly availableDevices: Readable<ReadonlyArray<MediaDeviceInfo>>;\n /**\n * Show this device in a device selector. It is the device identified by\n * the captured track, or the first candidate if there is no match.\n * It can differ from the saved preference and remains available while\n * idle. An empty device list gives `undefined`.\n */\n readonly activeDevice: Readable<MediaDeviceInfo | undefined>;\n /** The preference is kept in `localStorage`. */\n setPreferredDevice(device: MediaDeviceInfo): void;\n /** Each device that gave a track that is not healthy. */\n onDeviceFailure(listener: (device: MediaDeviceInfo) => void): () => void;\n /** Releases the hardware and all internal resources. */\n dispose(): Promise<void>;\n}\n\nexport interface ScreenShareTrackOptions {\n constraints?: MediaTrackConstraints;\n /** The broadcast is started at the start. Default: false. */\n broadcasting?: boolean;\n}\n\nexport interface ScreenShareSourceOptions {\n /** The source is enabled at the start. Default: false. */\n enabled?: boolean;\n /** Keeps the screen share acquired while the broadcast is stopped. */\n keepSourceAlive?: boolean;\n /** `false` asks for no audio. Default: true. */\n audio?: boolean | ScreenShareTrackOptions;\n video?: boolean | ScreenShareTrackOptions;\n}\n\nexport type ScreenShareTrack = Omit<\n TrackSource,\n \"isEnabled\" | \"enable\" | \"disable\" | \"toggleEnabled\"\n>;\n\nexport interface ScreenShareSource {\n readonly audio: ScreenShareTrack;\n readonly video: ScreenShareTrack;\n readonly isEnabled: Readable<boolean>;\n /** True when the audio or the video broadcasts. */\n readonly isBroadcasting: Readable<boolean>;\n enable(): void;\n disable(): void;\n toggleEnabled(): void;\n /** Starts the two tracks. The browser prompt shows. */\n startBroadcasting(): void;\n stopBroadcasting(): void;\n toggleBroadcasting(): void;\n dispose(): Promise<void>;\n}\n\nexport interface AudioSinkOptions {\n /** An `<audio>` element. */\n audioElement: AudioSinkElement;\n /** The audio output device at the start. */\n sinkId?: string;\n}\n\nexport interface AudioSink {\n /**\n * Plays the track of the `Readable`. A new track replaces the track\n * before it. Returns a function that removes the track.\n */\n attach(track: Readable<MediaStreamTrack | undefined>): () => void;\n /** False in a browser that cannot select the audio output device. */\n readonly isSinkIdSupported: boolean;\n /** Rejects with a `SinkError`. */\n setSinkId(sinkId: string): Promise<void>;\n /** The audio output devices. */\n readonly availableDevices: Readable<ReadonlyArray<MediaDeviceInfo>>;\n /** False when the browser blocked the element. */\n readonly isPlaying: Readable<boolean>;\n /** Removes all tracks from the element and stops the attachments. */\n dispose(): Promise<void>;\n}\n\n/**\n * A handle of the Effect core that is made at the first use. The module\n * and the source functions can thus be used where there is no browser.\n */\nclass Lazy<Handle> {\n /** The handle, after it is made. */\n ready: Handle | undefined;\n private started: Promise<Handle> | undefined;\n private scope: Scope.Closeable | undefined;\n private disposed = false;\n private readonly wires: Array<(handle: Handle) => () => void> = [];\n private stops: Array<() => void> = [];\n\n constructor(\n readonly runtime: () => SourcesRuntime,\n private readonly make: Effect.Effect<\n Handle,\n never,\n Scope.Scope | SourceServices\n >\n ) {}\n\n ensure = (): Promise<Handle> => {\n this.started ??= this.runtime()\n .runPromise(\n Effect.gen({ self: this }, function* () {\n const scope = yield* Scope.make();\n this.scope = scope;\n return yield* this.make.pipe(Scope.provide(scope));\n })\n )\n .then((handle) => {\n if (!this.disposed) {\n this.ready = handle;\n // From here, each state value follows the handle, also with no\n // subscriber, so that `get()` is always correct.\n this.stops = this.wires.map((wire) => wire(handle));\n }\n return handle;\n });\n return this.started;\n };\n\n /**\n * Runs a command that only changes a state. After the handle is made,\n * the command runs synchronously, inside the event that called it, so\n * that the browser sees the user gesture.\n */\n command = (effect: (handle: Handle) => Effect.Effect<void>): void => {\n if (this.disposed) return;\n if (this.ready !== undefined) {\n this.runtime().runSync(effect(this.ready));\n } else {\n void this.ensure().then((handle) => {\n if (!this.disposed) this.runtime().runSync(effect(handle));\n });\n }\n };\n\n /** Calls the listener with each value of the stream of the handle. */\n listen = <A>(\n stream: (handle: Handle) => Stream.Stream<A>,\n listener: (value: A) => void\n ): (() => void) => {\n let stop: (() => void) | undefined;\n let stopped = false;\n void this.ensure().then((handle) => {\n if (!stopped) stop = forward(this.runtime(), stream(handle), listener);\n });\n return () => {\n stopped = true;\n stop?.();\n };\n };\n\n /**\n * A value of the handle. The first subscriber of one of the values makes\n * the handle. Before that, the value is the initial value.\n */\n state = <A>(\n initial: A,\n subscribable: (handle: Handle) => Subscribable<A>\n ): Store<A> => {\n const store = new Store<A>(initial, {\n onActive: () => {\n void this.ensure();\n return () => {};\n }\n });\n this.wires.push((handle) =>\n forward(this.runtime(), subscribable(handle).changes, store.set)\n );\n return store;\n };\n\n /** A track of the handle. It is `undefined` with no subscriber. */\n track = (\n stream: (handle: Handle) => Stream.Stream<MediaStreamTrack>\n ): Store<MediaStreamTrack | undefined> => {\n const store: Store<MediaStreamTrack | undefined> = new Store<\n MediaStreamTrack | undefined\n >(undefined, {\n onActive: () => {\n const stop = this.listen(stream, store.set);\n return () => {\n stop();\n store.set(undefined);\n };\n }\n });\n return store;\n };\n\n async run(f: (h: Handle) => Effect.Effect<void, unknown>) {\n const h = this.ready ?? (await this.ensure());\n if (this.disposed) throw new Error(\"Source disposed\");\n return this.runtime().runPromise(f(h));\n }\n dispose = async (): Promise<void> => {\n this.disposed = true;\n this.ready = undefined;\n for (const stop of this.stops.splice(0)) stop();\n if (this.started === undefined) return;\n await this.started;\n if (this.scope !== undefined) {\n await this.runtime().runPromise(Scope.close(this.scope, Exit.void));\n }\n };\n\n /**\n * A child scope of the scope of the handle. `dispose()` closes it. It is\n * `undefined` after `dispose`.\n */\n childScope = async (): Promise<Scope.Closeable | undefined> => {\n if (this.disposed) return undefined;\n await this.ensure();\n if (this.disposed || this.scope === undefined) return undefined;\n return Scope.forkUnsafe(this.scope);\n };\n}\n\nconst toCoreTransform =\n (transform: TrackTransform): CoreTransform =>\n (track) =>\n Effect.gen(function* () {\n const controller = yield* Effect.acquireRelease(\n Effect.sync(() => new AbortController()),\n (made) => Effect.sync(() => made.abort())\n );\n return yield* Effect.tryPromise(async () =>\n transform(track, { signal: controller.signal })\n );\n });\n\ntype CoreTrack<E> = Pick<\n CoreTrackSource<E>,\n | \"broadcastTrack\"\n | \"localMonitorTrack\"\n | \"isBroadcasting\"\n | \"stopBroadcasting\"\n | \"errors\"\n | \"addTransform\"\n>;\n\n/** The part of a broadcast track that has no source flag. */\nconst plainTrack = <Handle, E extends SourceError>(\n lazy: Lazy<Handle>,\n pick: (handle: Handle) => CoreTrack<E>\n): Omit<ScreenShareTrack, \"startBroadcasting\" | \"toggleBroadcasting\"> => ({\n broadcastTrack: lazy.track((handle) => pick(handle).broadcastTrack),\n localMonitorTrack: lazy.track((handle) => pick(handle).localMonitorTrack),\n isBroadcasting: lazy.state(false, (handle) => pick(handle).isBroadcasting),\n stopBroadcasting: () =>\n lazy.command((handle) => pick(handle).stopBroadcasting),\n onError: (listener) => lazy.listen((handle) => pick(handle).errors, listener),\n addTransform: (transform) => {\n const added = lazy.childScope().then((scope) => {\n const handle = lazy.ready;\n if (scope === undefined || handle === undefined) return undefined;\n return lazy.runtime().runPromise(\n Effect.gen(function* () {\n yield* pick(handle)\n .addTransform(toCoreTransform(transform))\n .pipe(Scope.provide(scope));\n return scope;\n })\n );\n });\n return () => {\n void added.then((scope) => {\n if (scope !== undefined) {\n void lazy.runtime().runPromise(Scope.close(scope, Exit.void));\n }\n });\n };\n }\n});\n\nconst plainDevice =\n (runtime: () => SourcesRuntime, make: typeof MicrophoneSource.make) =>\n (options: DeviceSourceOptions = {}): DeviceSource => {\n const lazy = new Lazy<CoreDeviceSource>(\n runtime,\n make({\n ...options,\n transforms: options.transforms?.map(toCoreTransform)\n })\n );\n return wrapDevice(lazy, (h) => h, lazy.dispose);\n };\nfunction wrapDevice<H>(\n lazy: Lazy<H>,\n pick: (h: H) => CoreDeviceSource,\n dispose: () => Promise<void>\n): DeviceSource {\n const permission = lazy.state<SafePermissionState>(\n \"unknown\",\n (handle) => pick(handle).permissionState\n );\n return {\n ...plainTrack(lazy, pick),\n startBroadcasting: () => lazy.run((h) => pick(h).startBroadcasting),\n toggleBroadcasting: () => lazy.run((h) => pick(h).toggleBroadcasting),\n isAcquiring: lazy.state(false, (h) => pick(h).isAcquiring),\n isAcquired: lazy.state(false, (h) => pick(h).isAcquired),\n acquire: () => lazy.run((h) => pick(h).acquire),\n release: () => lazy.run((h) => pick(h).release),\n permissionState: permission,\n availableDevices: lazy.state<ReadonlyArray<MediaDeviceInfo>>(\n [],\n (handle) => pick(handle).availableDevices\n ),\n activeDevice: lazy.state<MediaDeviceInfo | undefined>(\n undefined,\n (handle) => pick(handle).activeDevice\n ),\n setPreferredDevice: (device) =>\n lazy.command((handle) => pick(handle).setPreferredDevice(device)),\n onDeviceFailure: (listener) =>\n lazy.listen((handle) => pick(handle).deviceFailures, listener),\n dispose\n };\n}\n\n/**\n * The media sources of the plain API on an internal runtime. Tests supply\n * the runtime and the fallback tracks, because the default fallback tracks\n * need a browser.\n */\nexport function makeSources(\n runtime: () => SourcesRuntime,\n fallbackTracks: {\n readonly audio?: Stream.Stream<MediaStreamTrack>;\n readonly video?: Stream.Stream<MediaStreamTrack>;\n } = {}\n) {\n return {\n /** Acquire both idle devices in one request or control either device independently. Dispose the pair when finished. */\n createMediaSources: (\n options: {\n microphone?: DeviceSourceOptions;\n camera?: DeviceSourceOptions;\n } = {}\n ) => {\n const convert = (o?: DeviceSourceOptions) => ({\n ...o,\n transforms: o?.transforms?.map(toCoreTransform)\n });\n const lazy = new Lazy(\n runtime,\n MediaSources.make({\n microphone: {\n ...convert(options.microphone),\n fallbackTrack: fallbackTracks.audio\n },\n camera: {\n ...convert(options.camera),\n fallbackTrack: fallbackTracks.video\n }\n })\n );\n return {\n microphone: wrapDevice(\n lazy,\n (h) => h.microphone,\n () => lazy.run((h) => h.microphone.release)\n ),\n camera: wrapDevice(\n lazy,\n (h) => h.camera,\n () => lazy.run((h) => h.camera.release)\n ),\n acquire: () => lazy.run((h) => h.acquire),\n release: () => lazy.run((h) => h.release),\n dispose: lazy.dispose\n };\n },\n /** The microphone: device selection, resilient acquisition, mute. */\n createMicrophoneSource: plainDevice(runtime, (options) =>\n MicrophoneSource.make({ ...options, fallbackTrack: fallbackTracks.audio })\n ),\n /** The camera: device selection, resilient acquisition, on and off. */\n createCameraSource: plainDevice(runtime, (options) =>\n CameraSource.make({ ...options, fallbackTrack: fallbackTracks.video })\n ),\n\n /** A screen share: an audio and a video track from one browser prompt. */\n createScreenShareSource: (\n options: ScreenShareSourceOptions = {}\n ): ScreenShareSource => {\n const lazy = new Lazy(\n runtime,\n CoreScreenShareSource.make({ ...options, fallbackTracks })\n );\n const track = (\n pick: (handle: CoreScreenShareSource) => CoreScreenShareTrack\n ) => ({\n ...plainTrack(lazy, pick),\n startBroadcasting: () => lazy.command((h) => pick(h).startBroadcasting),\n toggleBroadcasting: () =>\n lazy.command((h) => pick(h).toggleBroadcasting)\n });\n return {\n audio: track((handle) => handle.audio),\n video: track((handle) => handle.video),\n isEnabled: lazy.state(\n options.enabled ?? false,\n (handle) => handle.isEnabled\n ),\n isBroadcasting: lazy.state(false, (handle) => handle.isBroadcasting),\n enable: () => lazy.command((handle) => handle.enable),\n disable: () => lazy.command((handle) => handle.disable),\n toggleEnabled: () => lazy.command((handle) => handle.toggleEnabled),\n startBroadcasting: () =>\n lazy.command((handle) => handle.startBroadcasting),\n stopBroadcasting: () =>\n lazy.command((handle) => handle.stopBroadcasting),\n toggleBroadcasting: () =>\n lazy.command((handle) => handle.toggleBroadcasting),\n dispose: lazy.dispose\n };\n },\n\n /** Plays pulled audio tracks in one `<audio>` element. */\n createAudioSink: (options: AudioSinkOptions): AudioSink => {\n const lazy = new Lazy(runtime, CoreAudioSink.make(options));\n // The element gets its media stream immediately.\n void lazy.ensure();\n return {\n attach: (track) => {\n const attached = lazy.childScope().then((scope) => {\n const handle = lazy.ready;\n if (scope === undefined || handle === undefined) return undefined;\n return lazy.runtime().runPromise(\n Effect.gen(function* () {\n yield* handle\n .attach(streamOf(track))\n .pipe(Scope.provide(scope));\n return scope;\n })\n );\n });\n return () => {\n void attached.then((scope) => {\n if (scope !== undefined) {\n void lazy.runtime().runPromise(Scope.close(scope, Exit.void));\n }\n });\n };\n },\n isSinkIdSupported: options.audioElement.setSinkId !== undefined,\n setSinkId: (sinkId) =>\n lazy\n .ensure()\n .then((handle) => settle(lazy.runtime(), handle.setSinkId(sinkId))),\n availableDevices: lazy.state<ReadonlyArray<MediaDeviceInfo>>(\n [],\n (handle) => handle.availableDevices\n ),\n isPlaying: lazy.state(false, (handle) => handle.isPlaying),\n dispose: lazy.dispose\n };\n }\n };\n}\n\nlet shared: SourcesRuntime | undefined;\n\n/** One runtime for all media sources of the page. Made at the first use. */\nexport const browserSourcesRuntime = (): SourcesRuntime => {\n shared ??= ManagedRuntime.make(\n Layer.provideMerge(\n Layer.mergeAll(\n MediaDevices.layerBrowser,\n DevicePreferences.layerLocalStorage\n ),\n runtimeServices({})\n )\n );\n return shared;\n};\n","import * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as ManagedRuntime from \"effect/ManagedRuntime\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Scope from \"effect/Scope\";\nimport * as Stream from \"effect/Stream\";\n\nimport { RealtimeClient as Core } from \"../effect/client/RealtimeClient\";\nimport { forward, runtimeServices, settle, streamOf } from \"./internal\";\nimport { isReadable, Store } from \"./Readable\";\n\nimport type { RealtimeConfig } from \"../effect/client/Config\";\nimport type { LogEntry, LogLevel } from \"./logging\";\nimport type { Readable } from \"./Readable\";\nimport type {\n ApiHistoryEntry,\n ConnectionStats,\n PullState,\n PushState,\n SessionState,\n TrackMetadata,\n TransceiverEvent\n} from \"./types\";\n\nexport interface RealtimeClientOptions {\n /** Path or full URL of the proxy route. Default: \"/realtime\". */\n prefix?: string;\n /** Added to the query string of each request. */\n apiExtraParams?: string | URLSearchParams;\n /** Added to each request. A function is called for each request. */\n headers?: HeadersInit | (() => HeadersInit);\n /** Skips the request for ICE servers. */\n iceServers?: RTCIceServer[];\n /** How many API requests and responses the history keeps. Default: 100. */\n maxApiHistory?: number;\n /** Use \"include\" for a cross-origin prefix. Default: \"same-origin\". */\n credentials?: RequestCredentials;\n /** Default: the level of `setLogLevel()`, which is \"warn\" at the start. */\n logLevel?: LogLevel;\n /** Replaces the `console` output. */\n logger?: (entry: LogEntry) => void;\n /** Retry delays. Default: 250 ms, factor 2, maximum 10 s, no end. */\n retry?: {\n /** Milliseconds. */\n initialDelay?: number;\n factor?: number;\n /** Milliseconds. */\n maxDelay?: number;\n /** After this number of attempts, the state becomes `Failed`. */\n maxAttempts?: number;\n };\n /**\n * Set to false to remove the `traceparent` and `b3` request headers, for\n * example for a cross-origin prefix. Default: true.\n */\n tracePropagation?: boolean;\n /**\n * Called when a request is redirected, for example by an expired login.\n * The requests continue to be tried again.\n */\n onAuthRedirect?: () => void;\n}\n\nexport interface PushedTrack {\n /** Stable for the life of the handle, also across reconnects. */\n readonly trackName: string;\n readonly state: Readable<PushState>;\n /**\n * `undefined` until the track is published, and during a reconnect. Send\n * each value to the parties that pull the track.\n */\n readonly metadata: Readable<TrackMetadata | undefined>;\n /** Rejects with a `SenderError`. */\n setSendEncodings(encodings: RTCRtpEncodingParameters[]): Promise<void>;\n /** Stops the push and closes the track on the SFU. */\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\nexport interface PulledTrack {\n readonly state: Readable<PullState>;\n /** `undefined` until the track arrives, and while it is pulled again. */\n readonly track: Readable<MediaStreamTrack | undefined>;\n /** Changes the simulcast layer. Rejects with an API error. */\n setPreferredRid(rid: string): Promise<void>;\n /** Stops the pull and closes the track on the SFU. */\n close(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\nexport interface RealtimeClient {\n readonly sessionState: Readable<SessionState>;\n /**\n * Publishes a track until `close()`. With a `Readable`, each new track\n * replaces the track before it, with no new negotiation.\n */\n push(\n source: MediaStreamTrack | Readable<MediaStreamTrack | undefined>,\n options?: { sendEncodings?: RTCRtpEncodingParameters[]; trackName?: string }\n ): PushedTrack;\n /**\n * Pulls a track until `close()`. With a `Readable`, new metadata pulls\n * the new track.\n */\n pull(\n metadata: TrackMetadata | Readable<TrackMetadata | undefined>,\n options?: { preferredRid?: string }\n ): PulledTrack;\n /** Each transceiver that is added (push) or resolved (pull). */\n onTransceiver(listener: (event: TransceiverEvent) => void): () => void;\n /**\n * The statistics of the open session and of its tracks, at each interval.\n * Nothing comes while no session is open. It does not keep a session open.\n */\n onStats(\n listener: (stats: ConnectionStats) => void,\n options?: {\n /** Milliseconds between two samples. Default: 2000. */\n interval?: number;\n }\n ): () => void;\n /** Each API request and response when it occurs. */\n onApiEvent(listener: (entry: ApiHistoryEntry) => void): () => void;\n /** The last API requests and responses. */\n getApiHistory(): ApiHistoryEntry[];\n /** Closes all handles, the session, and the internal runtime. */\n dispose(): Promise<void>;\n [Symbol.asyncDispose](): Promise<void>;\n}\n\nfunction retrySchedule(retry: NonNullable<RealtimeClientOptions[\"retry\"]>) {\n const maxDelay = Duration.millis(retry.maxDelay ?? 10_000);\n const delays = Schedule.exponential(\n Duration.millis(retry.initialDelay ?? 250),\n retry.factor ?? 2\n ).pipe(\n Schedule.modifyDelay(({ duration }) =>\n Effect.succeed(Duration.min(duration, maxDelay))\n )\n );\n return retry.maxAttempts === undefined\n ? delays\n : Schedule.max([delays, Schedule.recurs(retry.maxAttempts)]);\n}\n\nconst toConfig = (options: RealtimeClientOptions): RealtimeConfig => {\n const schedule =\n options.retry === undefined ? undefined : retrySchedule(options.retry);\n return {\n prefix: options.prefix,\n apiExtraParams: options.apiExtraParams,\n headers: options.headers,\n iceServers: options.iceServers,\n maxApiHistory: options.maxApiHistory,\n tracePropagation: options.tracePropagation,\n sessionRetry: schedule,\n trackRetry: schedule\n };\n};\n\n/** Pushes local tracks to the Realtime SFU and pulls remote tracks from it. */\nexport function createRealtimeClient(\n options: RealtimeClientOptions = {}\n): RealtimeClient {\n return createRealtimeFromLayer(\n options,\n Core.layerBrowser({\n ...toConfig(options),\n credentials: options.credentials\n })\n );\n}\n\n/** The configuration of the core for these options. Tests use it. */\nexport const coreConfig = toConfig;\n\n/** `createRealtimeClient` on a different layer of the core. Tests use it. */\nexport function createRealtimeFromLayer(\n options: RealtimeClientOptions,\n layer: Layer.Layer<Core>\n): RealtimeClient {\n const runtime = ManagedRuntime.make(\n Layer.provideMerge(layer, runtimeServices(options))\n );\n const core = runtime.runPromise(\n Effect.gen(function* () {\n return yield* Core;\n })\n );\n /** Runs when the core is ready. Returns a function that stops it. */\n const whenReady = (start: (core: Core[\"Service\"]) => () => void) => {\n let stop: (() => void) | undefined;\n let stopped = false;\n void core.then((service) => {\n if (!stopped) stop = start(service);\n });\n return () => {\n stopped = true;\n stop?.();\n };\n };\n\n const session = new Store<SessionState>({ _tag: \"Idle\" });\n whenReady((service) =>\n forward(runtime, service.sessionState.changes, session.set)\n );\n\n const maxHistory = Math.max(1, options.maxApiHistory ?? 100);\n const history: ApiHistoryEntry[] = [];\n // One error for each series of redirects. A response that is not a\n // redirect starts the next series.\n let loggedAuthRedirect = false;\n whenReady((service) =>\n forward(runtime, service.apiEvents, (entry) => {\n history.push(entry);\n if (history.length > maxHistory) history.shift();\n if (entry.type !== \"response\") return;\n // With `redirect: \"manual\"`, a redirect has status 0.\n if (entry.status !== 0) {\n loggedAuthRedirect = false;\n return;\n }\n if (options.onAuthRedirect !== undefined) {\n options.onAuthRedirect();\n } else if (!loggedAuthRedirect) {\n loggedAuthRedirect = true;\n runtime.runFork(\n Effect.logError(\n \"The request was redirected and no onAuthRedirect handler is set\"\n ).pipe(Effect.annotateLogs({ endpoint: entry.endpoint }))\n );\n }\n })\n );\n\n /** The handles that are open. `dispose` closes them. */\n const open = new Set<() => Promise<void>>();\n\n /**\n * Starts a push or a pull in its own scope. `close` waits for the start,\n * so that a close immediately after the start is safe.\n */\n const start = <Handle>(\n make: (\n service: Core[\"Service\"],\n scope: Scope.Scope\n ) => Effect.Effect<Handle>,\n onClosed: () => void\n ) => {\n let closing: Promise<void> | undefined;\n const started = core.then((service) =>\n runtime.runPromise(\n Effect.gen(function* () {\n const scope = yield* Scope.make();\n return { scope, handle: yield* make(service, scope) };\n })\n )\n );\n const close = () => {\n closing ??= started\n .then(({ scope }) => runtime.runPromise(Scope.close(scope, Exit.void)))\n .then(() => {\n open.delete(close);\n onClosed();\n });\n return closing;\n };\n open.add(close);\n return { handle: started.then(({ handle }) => handle), close };\n };\n\n const realtime: RealtimeClient = {\n sessionState: session,\n\n push: (source, pushOptions = {}) => {\n const trackName = pushOptions.trackName ?? crypto.randomUUID();\n const state = new Store<PushState>({ _tag: \"WaitingForTrack\" });\n const metadata = new Store<TrackMetadata | undefined>(undefined);\n const setState = (next: PushState) => {\n metadata.set(next._tag === \"Published\" ? next.metadata : undefined);\n state.set(next);\n };\n const { handle, close } = start(\n (service, scope) =>\n Effect.gen(function* () {\n const pushed = yield* service.push<unknown>(\n isReadable(source) ? streamOf(source) : Stream.make(source),\n { sendEncodings: pushOptions.sendEncodings, trackName }\n );\n yield* pushed.state.changes.pipe(\n Stream.runForEach((next) => Effect.sync(() => setState(next))),\n Effect.forkScoped\n );\n return pushed;\n }).pipe(Scope.provide(scope)),\n () => setState({ _tag: \"Closed\" })\n );\n return {\n trackName,\n state,\n metadata,\n setSendEncodings: (encodings) =>\n handle.then((pushed) =>\n settle(\n runtime,\n pushed\n .setSendEncodings(encodings)\n .pipe(\n Effect.tapError((error) =>\n Effect.logWarning(\"setSendEncodings failed\", error)\n )\n )\n )\n ),\n close,\n [Symbol.asyncDispose]: close\n };\n },\n\n pull: (target, pullOptions = {}) => {\n const state = new Store<PullState>({ _tag: \"WaitingForMetadata\" });\n const track = new Store<MediaStreamTrack | undefined>(undefined);\n const setState = (next: PullState) => {\n track.set(next._tag === \"Live\" ? next.track : undefined);\n state.set(next);\n };\n const { handle, close } = start(\n (service, scope) =>\n Effect.gen(function* () {\n const pulled = yield* service.pull<unknown>(\n isReadable(target) ? streamOf(target) : target,\n pullOptions\n );\n yield* pulled.state.changes.pipe(\n Stream.runForEach((next) => Effect.sync(() => setState(next))),\n Effect.forkScoped\n );\n return pulled;\n }).pipe(Scope.provide(scope)),\n () => setState({ _tag: \"Closed\" })\n );\n return {\n state,\n track,\n setPreferredRid: (rid) =>\n handle.then((pulled) =>\n settle(\n runtime,\n pulled\n .setPreferredRid(rid)\n .pipe(\n Effect.tapError((error) =>\n Effect.logWarning(\"setPreferredRid failed\", error)\n )\n )\n )\n ),\n close,\n [Symbol.asyncDispose]: close\n };\n },\n\n onTransceiver: (listener) =>\n whenReady((service) => forward(runtime, service.transceivers, listener)),\n onStats: (listener, statsOptions = {}) =>\n whenReady((service) =>\n forward(\n runtime,\n service.stats(\n statsOptions.interval === undefined\n ? {}\n : { interval: Duration.millis(statsOptions.interval) }\n ),\n listener\n )\n ),\n onApiEvent: (listener) =>\n whenReady((service) => forward(runtime, service.apiEvents, listener)),\n getApiHistory: () => [...history],\n\n dispose: async () => {\n await Promise.all([...open].map((close) => close()));\n await runtime.dispose();\n },\n [Symbol.asyncDispose]: () => realtime.dispose()\n };\n return realtime;\n}\n","import { browserSourcesRuntime, makeSources } from \"./sources\";\n\nexport { createRealtimeClient } from \"./RealtimeClient\";\nexport type {\n RealtimeClient,\n RealtimeClientOptions,\n PulledTrack,\n PushedTrack\n} from \"./RealtimeClient\";\nexport { writable } from \"./Readable\";\nexport type { InteropObservable, Readable, Writable } from \"./Readable\";\nexport { setLogLevel } from \"./logging\";\nexport type { LogEntry, LogLevel } from \"./logging\";\nexport type {\n AudioSink,\n AudioSinkOptions,\n TrackSource,\n DeviceSource,\n DeviceSourceOptions,\n ScreenShareSource,\n ScreenShareSourceOptions,\n ScreenShareTrack,\n ScreenShareTrackOptions,\n TrackTransform\n} from \"./sources\";\nexport type * from \"./types\";\n\nconst sources = makeSources(browserSourcesRuntime);\n\n/** The microphone: device selection, resilient acquisition, mute. */\nexport const createMicrophoneSource = sources.createMicrophoneSource;\n/** The camera: device selection, resilient acquisition, on and off. */\nexport const createCameraSource = sources.createCameraSource;\n/** A screen share: an audio and a video track from one browser prompt. */\nexport const createScreenShareSource = sources.createScreenShareSource;\n/** Plays pulled audio tracks in one `<audio>` element. */\nexport const createAudioSink = sources.createA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