@midsummer-ai/sdk 0.1.0-staging.4480 → 0.1.0-staging.4486

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.
@@ -0,0 +1,2 @@
1
+ import { a as CallToken, c as Layer, d as TrackName, f as WireParticipant, i as CallOp, l as Sdp, m as WireSignal, n as CALL_STATUS, o as CallWire, p as WireRoom, r as CallErrorCode, s as IceServer, t as CALL_OPS, u as TRACK_KINDS } from "../protocol-BeBvbfKf.mjs";
2
+ export { CALL_OPS, CALL_STATUS, CallErrorCode, CallOp, CallToken, CallWire, IceServer, Layer, Sdp, TRACK_KINDS, TrackName, WireParticipant, WireRoom, WireSignal };
@@ -0,0 +1,33 @@
1
+ //#region src/calls/protocol.ts
2
+ const TRACK_KINDS = {
3
+ mic: "audio",
4
+ camera: "video",
5
+ screen: "video",
6
+ "screen-audio": "audio"
7
+ };
8
+ /** The ops, in a list, for a server that serves them. */
9
+ const CALL_OPS = [
10
+ "join",
11
+ "publish",
12
+ "unpublish",
13
+ "pull",
14
+ "answer",
15
+ "layer",
16
+ "unpull",
17
+ "data",
18
+ "signal",
19
+ "watch",
20
+ "leave"
21
+ ];
22
+ /** Each code's status on the wire. */
23
+ const CALL_STATUS = {
24
+ invalid: 400,
25
+ quota: 402,
26
+ forbidden: 403,
27
+ "not-found": 404,
28
+ full: 409,
29
+ ended: 410,
30
+ unavailable: 503
31
+ };
32
+ //#endregion
33
+ export { CALL_OPS, CALL_STATUS, TRACK_KINDS };
@@ -0,0 +1,56 @@
1
+ import { d as TrackName } from "../protocol-BeBvbfKf.mjs";
2
+ import { Call, CallError, CallState, LocalTrack, Participant, Rtc, TokenSource } from "./index.mjs";
3
+ import { AudioHTMLAttributes, ReactNode, VideoHTMLAttributes } from "react";
4
+ //#region src/calls/react.d.ts
5
+ /** A room to join, with the token the app's server made for it. */
6
+ interface JoiningProps {
7
+ readonly room: string;
8
+ readonly token: TokenSource;
9
+ readonly url?: string;
10
+ readonly rtc?: Rtc;
11
+ /** Receive others' videos as they publish them, up to 9: true unless the page chooses with `receive`. */
12
+ readonly autoVideo?: boolean;
13
+ /** Joins as it mounts: true unless the page joins with `useJoin()`. */
14
+ readonly autoJoin?: boolean;
15
+ readonly call?: never;
16
+ readonly children?: ReactNode;
17
+ }
18
+ /** A call already joined, shown as it is. */
19
+ interface JoinedProps {
20
+ readonly call: Call;
21
+ readonly room?: never;
22
+ readonly token?: never;
23
+ readonly children?: ReactNode;
24
+ }
25
+ type CallProviderProps = JoiningProps | JoinedProps;
26
+ /** Joins `room` for the components inside it and leaves when it unmounts, or gives them a `call` joined elsewhere. */
27
+ declare function CallProvider(props: CallProviderProps): ReactNode;
28
+ /** The call, or undefined while it joins and when it couldn't. */
29
+ declare function useCall(): Call | undefined;
30
+ /** Where the call is: `connecting` until it joins, then as `call.state` says. */
31
+ declare function useCallState(): CallState;
32
+ /** Why the call failed, once `useCallState()` is `failed`. */
33
+ declare function useCallError(): CallError | undefined;
34
+ /** Joins, with `autoJoin={false}`; joining twice joins once. */
35
+ declare function useJoin(): () => Promise<Call>;
36
+ /** Everyone else in the call. */
37
+ declare function useParticipants(): ReadonlyArray<Participant>;
38
+ /** The tracks received, from one participant or from everyone, each with whose it is and its name. */
39
+ declare function useTracks(participantId?: string): ReadonlyArray<{
40
+ readonly participant: Participant;
41
+ readonly name: TrackName;
42
+ readonly track: MediaStreamTrack;
43
+ }>;
44
+ /** What this call publishes, each with whether it is muted. */
45
+ declare function useLocalTracks(): ReadonlyArray<LocalTrack>;
46
+ /** Shows a track in a `<video>`, muted and playing inline unless told otherwise. */
47
+ declare function Video({ track, muted, ...props }: {
48
+ readonly track: MediaStreamTrack | undefined;
49
+ readonly muted?: boolean;
50
+ } & Omit<VideoHTMLAttributes<HTMLVideoElement>, "muted">): ReactNode;
51
+ /** Plays a track in an `<audio>` that shows nothing. */
52
+ declare function Audio({ track, ...props }: {
53
+ readonly track: MediaStreamTrack | undefined;
54
+ } & AudioHTMLAttributes<HTMLAudioElement>): ReactNode;
55
+ //#endregion
56
+ export { Audio, CallProvider, CallProviderProps, JoinedProps, JoiningProps, Video, useCall, useCallError, useCallState, useJoin, useLocalTracks, useParticipants, useTracks };
@@ -0,0 +1,225 @@
1
+ "use client";
2
+ import { join } from "./index.mjs";
3
+ import { createContext, createElement, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
4
+ //#region src/calls/react.ts
5
+ /**
6
+ * `@midsummer-ai/sdk/calls/react`: a call in React, built from the same blocks as `@midsummer-ai/sdk/calls`.
7
+ *
8
+ * import { CallProvider, useCall, useCallState, useParticipants, useTracks, Video, Audio } from "@midsummer-ai/sdk/calls/react"
9
+ *
10
+ * root.render(<CallProvider room="standup" token={() => fetch("/call-token?room=standup").then((r) => r.json())}><Grid /></CallProvider>)
11
+ *
12
+ * function Grid() {
13
+ * const call = useCall() // undefined while it joins
14
+ * const state = useCallState() // "connecting", "waiting", "in-call" …
15
+ * const tracks = useTracks() // every track received, with whose it is
16
+ * return <>
17
+ * <button onClick={() => call?.publish({ mic: true, camera: true })}>Join with camera</button>
18
+ * {tracks.map(({ participant, name, track }) => track.kind === "video"
19
+ * ? <Video key={`${participant.id}/${name}`} track={track} />
20
+ * : <Audio key={`${participant.id}/${name}`} track={track} />)}
21
+ * </>
22
+ * }
23
+ *
24
+ * The provider joins when it mounts and leaves when it unmounts, or joins when `useJoin()`'s function is called with
25
+ * `autoJoin={false}`. It joins again when `room` changes; a `token` function given anew on each render is fine, as the
26
+ * one given last is the one asked.
27
+ *
28
+ * A call joined elsewhere goes in as `call` instead of `room` and `token`: the components inside show it as it is, and
29
+ * leaving it stays with whoever joined it. Anything shaped like a `Call` will do, such as a stand-in that plays a call's
30
+ * states for a page of examples or a test:
31
+ *
32
+ * const call = await join("standup", { token })
33
+ * root.render(<CallProvider call={call}><Grid /></CallProvider>)
34
+ *
35
+ * React is a peer dependency: a project that does not import this entry does not need it.
36
+ */
37
+ const CallContext = createContext(void 0);
38
+ const NONE = [];
39
+ const noop = () => {};
40
+ /** Joins `room` for the components inside it and leaves when it unmounts, or gives them a `call` joined elsewhere. */
41
+ function CallProvider(props) {
42
+ return props.call !== void 0 ? createElement(JoinedCall, props) : createElement(JoiningCall, props);
43
+ }
44
+ /** A call joined elsewhere: its state as its events say, and nothing joined or left here. */
45
+ function JoinedCall({ call, children }) {
46
+ const holder = useMemo(() => {
47
+ const heldOf = () => ({
48
+ call,
49
+ state: call.state,
50
+ ...call.error ? { error: call.error } : {}
51
+ });
52
+ let held = heldOf();
53
+ return {
54
+ get: () => held,
55
+ subscribe: (fn) => call.on("state", () => {
56
+ held = heldOf();
57
+ fn();
58
+ }),
59
+ join: () => Promise.resolve(call)
60
+ };
61
+ }, [call]);
62
+ return createElement(CallContext.Provider, { value: holder }, children);
63
+ }
64
+ function JoiningCall({ room, token, url, rtc, autoVideo, autoJoin = true, children }) {
65
+ const latest = useRef(token);
66
+ latest.current = token;
67
+ const holder = useMemo(() => {
68
+ let held = { state: "connecting" };
69
+ let joining;
70
+ let gone = false;
71
+ const listeners = /* @__PURE__ */ new Set();
72
+ const set = (next) => {
73
+ held = next;
74
+ for (const fn of [...listeners]) fn();
75
+ };
76
+ const tokenNow = () => {
77
+ const given = latest.current;
78
+ return typeof given === "function" ? () => {
79
+ const now = latest.current;
80
+ return typeof now === "function" ? now() : Promise.resolve(now);
81
+ } : given;
82
+ };
83
+ const optionsNow = () => ({
84
+ token: tokenNow(),
85
+ ...url !== void 0 ? { url } : {},
86
+ ...rtc ? { rtc } : {},
87
+ ...autoVideo !== void 0 ? { autoVideo } : {}
88
+ });
89
+ return {
90
+ get: () => held,
91
+ subscribe(fn) {
92
+ listeners.add(fn);
93
+ return () => {
94
+ listeners.delete(fn);
95
+ };
96
+ },
97
+ join() {
98
+ joining ??= join(room, optionsNow()).then((call) => {
99
+ if (gone) {
100
+ call.leave();
101
+ return call;
102
+ }
103
+ set({
104
+ call,
105
+ state: call.state
106
+ });
107
+ call.on("state", (state) => set({
108
+ call,
109
+ state,
110
+ ...call.error ? { error: call.error } : {}
111
+ }));
112
+ return call;
113
+ }, (error) => {
114
+ if (!gone) set({
115
+ state: "failed",
116
+ error
117
+ });
118
+ throw error;
119
+ });
120
+ return joining;
121
+ },
122
+ leave() {
123
+ gone = true;
124
+ held.call?.leave();
125
+ }
126
+ };
127
+ }, [
128
+ room,
129
+ url,
130
+ rtc,
131
+ autoVideo
132
+ ]);
133
+ useEffect(() => {
134
+ let stopped = false;
135
+ if (autoJoin) queueMicrotask(() => {
136
+ if (!stopped) holder.join().catch(noop);
137
+ });
138
+ return () => {
139
+ stopped = true;
140
+ holder.leave();
141
+ };
142
+ }, [holder, autoJoin]);
143
+ return createElement(CallContext.Provider, { value: holder }, children);
144
+ }
145
+ function useHolder(what) {
146
+ const holder = useContext(CallContext);
147
+ if (!holder) throw new Error(`${what} is used inside a <CallProvider>.`);
148
+ return holder;
149
+ }
150
+ function useHeld() {
151
+ const holder = useHolder("A call hook");
152
+ return useSyncExternalStore(holder.subscribe, holder.get, holder.get);
153
+ }
154
+ /** The call, or undefined while it joins and when it couldn't. */
155
+ function useCall() {
156
+ return useHeld().call;
157
+ }
158
+ /** Where the call is: `connecting` until it joins, then as `call.state` says. */
159
+ function useCallState() {
160
+ return useHeld().state;
161
+ }
162
+ /** Why the call failed, once `useCallState()` is `failed`. */
163
+ function useCallError() {
164
+ return useHeld().error;
165
+ }
166
+ /** Joins, with `autoJoin={false}`; joining twice joins once. */
167
+ function useJoin() {
168
+ return useHolder("useJoin").join;
169
+ }
170
+ /** Watches one of the call's values, re-rendering when its event says it changed. */
171
+ function useCallValue(event, read, none) {
172
+ const call = useCall();
173
+ return useSyncExternalStore((fn) => call ? call.on(event, fn) : noop, () => call ? read(call) : none, () => call ? read(call) : none);
174
+ }
175
+ /** Everyone else in the call. */
176
+ function useParticipants() {
177
+ return useCallValue("participants", (call) => call.participants, NONE);
178
+ }
179
+ /** The tracks received, from one participant or from everyone, each with whose it is and its name. */
180
+ function useTracks(participantId) {
181
+ const participants = useParticipants();
182
+ return useMemo(() => participants.filter((participant) => participantId === void 0 || participant.id === participantId).flatMap((participant) => Object.entries(participant.received).flatMap(([name, track]) => track ? [{
183
+ participant,
184
+ name,
185
+ track
186
+ }] : [])), [participants, participantId]);
187
+ }
188
+ /** What this call publishes, each with whether it is muted. */
189
+ function useLocalTracks() {
190
+ return useCallValue("local", (call) => call.local, NONE);
191
+ }
192
+ /** Shows a track in a `<video>`, muted and playing inline unless told otherwise. */
193
+ function Video({ track, muted = true, ...props }) {
194
+ const ref = useAttached(track);
195
+ return createElement("video", {
196
+ autoPlay: true,
197
+ playsInline: true,
198
+ ...props,
199
+ muted,
200
+ ref
201
+ });
202
+ }
203
+ /** Plays a track in an `<audio>` that shows nothing. */
204
+ function Audio({ track, ...props }) {
205
+ const ref = useAttached(track);
206
+ return createElement("audio", {
207
+ autoPlay: true,
208
+ ...props,
209
+ ref
210
+ });
211
+ }
212
+ function useAttached(track) {
213
+ const ref = useRef(null);
214
+ useEffect(() => {
215
+ const element = ref.current;
216
+ if (!element) return;
217
+ element.srcObject = track ? new MediaStream([track]) : null;
218
+ return () => {
219
+ element.srcObject = null;
220
+ };
221
+ }, [track]);
222
+ return ref;
223
+ }
224
+ //#endregion
225
+ export { Audio, CallProvider, Video, useCall, useCallError, useCallState, useJoin, useLocalTracks, useParticipants, useTracks };
@@ -0,0 +1,22 @@
1
+ import { a as CallToken } from "../protocol-BeBvbfKf.mjs";
2
+ import { CallTokenInput } from "./index.mjs";
3
+ //#region src/calls/stand-in.d.ts
4
+ interface CallsStandIn {
5
+ /** Serves the call wire at `<any path>/<op>`, `POST <any path>/token` to make a token, and the browser's preflight. */
6
+ fetch(request: Request): Promise<Response>;
7
+ /** A token for a room, as the app's server makes one. */
8
+ token(input: CallTokenInput): Promise<CallToken>;
9
+ /** Ends a room, as `midsummer call room end` does: everyone leaves, and tokens made before now join no more. */
10
+ end(room: string): Promise<void>;
11
+ }
12
+ interface StandInOptions {
13
+ /** The time presence and tokens are kept by: the system's when left out. */
14
+ readonly clock?: () => number;
15
+ /** Signs tokens: 32 characters or more, made up when left out. */
16
+ readonly secret?: string;
17
+ /** Where it is served, given with each token `token` makes. A token made through `fetch` gets the address it was asked at. */
18
+ readonly url?: string;
19
+ }
20
+ declare function standIn(options?: StandInOptions): CallsStandIn;
21
+ //#endregion
22
+ export { CallsStandIn, StandInOptions, standIn };