### Install dependencies and run dev server Source: https://github.com/cloudflare/meet/blob/main/README.md Install npm dependencies and start the development server. Open http://127.0.0.1:8787 to access the app. ```sh npm install npm run dev ``` -------------------------------- ### useCopyToClipboard usage example Source: https://github.com/cloudflare/meet Example usage of `useCopyToClipboard` with a button that copies a room URL and shows 'Copied!' for 2 seconds. ```TypeScript const [copied, copy] = useCopyToClipboard() ``` -------------------------------- ### Login to Wrangler Source: https://github.com/cloudflare/meet/blob/main/README.md Ensure wrangler is installed and you are logged in before deploying. ```sh wrangler login ``` -------------------------------- ### Example: handle permission errors with useUserMedia Source: https://github.com/cloudflare/meet Shows how to react to audioUnavailableReason by logging and turning off the mic. ```ts const userMedia = useUserMedia({ micDeviceId, cameraDeviceId }) // Example: handle permission errors useEffect(() => { if (userMedia.audioUnavailableReason) { console.error(userMedia.audioUnavailableReason) userMedia.turnMicOff() } }, [userMedia.audioUnavailableReason, userMedia]) ``` -------------------------------- ### GET /new Source: https://github.com/cloudflare/meet Redirects to a new room with a generated nanoid of length 8, preserving query parameters. ```APIDOC ## [GET] /new ### Description Redirects to a new room with a generated nanoid of length 8, preserving query parameters. ### Method GET ### Endpoint /new ### Response #### Redirect (302) - Redirects to `/{nanoid(8)}` plus existing query params. ``` -------------------------------- ### debugTap usage example Source: https://github.com/cloudflare/meet Example of using debugTap in a pipe to log emissions from a source observable. ```typescript source$.pipe(debugTap('track$')).subscribe() ``` -------------------------------- ### usePeerConnection usage example Source: https://github.com/cloudflare/meet Example usage of usePeerConnection with maxApiHistory, apiExtraParams, and iceServers. The apiExtraParams sets correlationId to the meetingId. ```ts const { partyTracks, iceConnectionState } = usePeerConnection({ maxApiHistory: 100, apiExtraParams: `correlationId=${meetingId}`, iceServers, }) ``` -------------------------------- ### Install wasm-pack with cargo Source: https://github.com/cloudflare/meet/blob/main/rust-mls-worker/README.md Install the wasm-pack tool using Cargo, as an alternative to the official installer. ```bash cargo install wasm-pack ``` -------------------------------- ### useUserMetadata usage example Source: https://github.com/cloudflare/meet Example of calling useUserMetadata with identity?.name ?? '' and accessing data.displayName — resolved display name or the raw email. ```ts const { data } = useUserMetadata(identity?.name ?? '') // data.displayName — resolved display name or the raw email ``` -------------------------------- ### GET / Source: https://github.com/cloudflare/meet Root loader that requires a username, otherwise redirects to /set-username. Validates CF_Authorization cookie freshness and returns user directory URL. ```APIDOC ## [GET] / ### Description Root loader that requires a username, otherwise redirects to /set-username. Validates CF_Authorization cookie freshness and returns user directory URL. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **userDirectoryUrl** (string) - The user directory URL from environment. #### Redirect (302) - Redirects to `/set-username?return-url=` when no identity is present. ``` -------------------------------- ### populateTraceLink utility Source: https://github.com/cloudflare/meet Returns undefined without a traceLink; otherwise copies the URL, sets start (now − 1h, in microseconds), end (now, microseconds), and tags to {"peer.SessionID": sessionID}, and returns the string. ```typescript export default function populateTraceLink( sessionID: string, traceLink?: string ) ``` -------------------------------- ### GET /api/debugInfo Source: https://github.com/cloudflare/meet Returns a 404 '404: Missing KV Binding' response when the FEEDBACK_STORAGE KV binding is not available. This endpoint is used to retrieve debug information. ```APIDOC ## [GET] /api/debugInfo ### Description Returns a 404 '404: Missing KV Binding' response when the FEEDBACK_STORAGE KV binding is not available. This endpoint is used to retrieve debug information. ### Method GET ### Endpoint /api/debugInfo ### Response #### Success Response (404) - **body** (string) - `'404: Missing KV Binding'` ### Error Handling - **404 '404: Missing KV Binding'** - Returned when `FEEDBACK_STORAGE` is not available. ``` -------------------------------- ### GET /site.webmanifest Source: https://github.com/cloudflare/meet Returns the static JSON web manifest for the application. Contains app name, icons, theme color, and display mode. ```APIDOC ## [GET] /site.webmanifest ### Description Returns the static JSON web manifest for the application. Contains app name, icons, theme color, and display mode. ### Method GET ### Endpoint /site.webmanifest ### Response #### Success Response (200) Static JSON web manifest with name 'Orange Meets', icons, theme color, and display: 'standalone'. ``` -------------------------------- ### GET /new, POST / Source: https://github.com/cloudflare/meet Returns a 302 redirect to a room. These endpoints are used to create or join a room. ```APIDOC ## [GET] /new, [POST] / ### Description Returns a 302 redirect to a room. These endpoints are used to create or join a room. ### Method GET, POST ### Endpoint /new, / ### Response #### Success Response (302) - **Location** (string) - Redirect target to the room. ### Error Handling - **302** - Redirect to a room. ``` -------------------------------- ### monitorAudioLevel usage example Source: https://github.com/cloudflare/meet Shows how to call monitorAudioLevel with a media stream track and a callback that logs the RMS value. The returned cleanup function should be called on unmount. ```ts const cleanup = monitorAudioLevel({ mediaStreamTrack: track, onMeasure: (vol) => console.log('RMS:', vol), intervalMs: 100, }) // later: cleanup() ``` -------------------------------- ### getScreenshare$({ contentHint }) Source: https://github.com/cloudflare/meet Function to get a screenshare observable with a content hint. ```APIDOC ## Function: getScreenshare$({ contentHint }) ### Description Function to get a screenshare observable with a content hint. ### Parameters - `contentHint` (string) - Required - Content hint for the screenshare. ``` -------------------------------- ### GET /api/debugInfo Source: https://github.com/cloudflare/meet Returns a 404 '404: Report not found' response when the KV key is absent. This endpoint is used to retrieve debug information. ```APIDOC ## [GET] /api/debugInfo ### Description Returns a 404 '404: Report not found' response when the KV key is absent. This endpoint is used to retrieve debug information. ### Method GET ### Endpoint /api/debugInfo ### Parameters #### Query Parameters - **id** (string) - Required - The identifier for the debug report. ### Response #### Success Response (404) - **body** (string) - `'404: Report not found'` ### Error Handling - **404 '404: Report not found'** - Returned when the KV key is absent. ``` -------------------------------- ### GET /set-username Source: https://github.com/cloudflare/meet Renders the username form. ```APIDOC ## [GET] /set-username ### Description Renders the username form. ### Method GET ### Endpoint /set-username ### Response #### Success Response (200) - Renders the form (no loader data). ``` -------------------------------- ### getPacketLossStats$ usage example Source: https://github.com/cloudflare/meet Example of subscribing to getPacketLossStats$ and updating a badge with the packet loss percentages. ```typescript const stats$ = getPacketLossStats$(partyTracks.peerConnection$) const sub = stats$.subscribe((s) => { updateBadge(s.inboundPacketLossPercentage, s.outboundPacketLossPercentage) }) ``` -------------------------------- ### POST /partytracks/* Source: https://github.com/cloudflare/meet Same as GET /partytracks/*, proxies the browser's partytracks client to Cloudflare Calls. ```APIDOC ## [POST] /partytracks/* ### Description Same as GET /partytracks/*, proxies the browser's partytracks client to Cloudflare Calls. ### Method POST ### Endpoint /partytracks/* ### Response #### Success Response (200) - Returns whatever `routePartyTracksRequest` returns. ``` -------------------------------- ### FIFOScheduler usage example Source: https://github.com/cloudflare/meet Shows how to use FIFOScheduler to run tasks strictly one after another in call order. ```ts const scheduler = new FIFOScheduler() // These run strictly one after another, in call order const a = await scheduler.schedule(async () => readState()) const b = await scheduler.schedule(async () => updateState(a)) ``` -------------------------------- ### GET / (root loader) Source: https://github.com/cloudflare/meet Returns a 302 redirect when no username is set or when the CF_Authorization cookie has expired. This is the root loader for the application. ```APIDOC ## [GET] / (root loader) ### Description Returns a 302 redirect when no username is set or when the CF_Authorization cookie has expired. This is the root loader for the application. ### Method GET ### Endpoint / ### Response #### Success Response (302) - **Location** (string) - Redirect target. ### Error Handling - **302** - Redirects to `/set-username?return-url=...` when no username is set. - **302** - Clears cookies and redirects when `CF_Authorization` has expired. ``` -------------------------------- ### initLogging Source: https://github.com/cloudflare/meet Initializes console_log at Level::Info and installs the console_error_panic_hook. Called once by worker.js after the WASM module loads. No arguments, returns nothing. ```APIDOC ## initLogging ### Description Initializes `console_log` at `Level::Info` and installs the `console_error_panic_hook`. Called once by `worker.js` after the WASM module loads. No arguments, returns nothing. ### Method Function ### Signature `pub fn initLogging()` ### Parameters None ### Returns Nothing ``` -------------------------------- ### useE2eeStatus(group, shownIds) Source: https://github.com/cloudflare/meet Hook to get E2EE status for a group. Requires shownIds including self. ```APIDOC ## Hook: useE2eeStatus(group, shownIds) ### Description Hook to get E2EE status for a group. Requires shownIds including self. ### Parameters - `group` (type not specified) - Required - The group. - `shownIds` (string[]) - Required - Array of shown IDs, must include self. ``` -------------------------------- ### GET / (index) loader Source: https://github.com/cloudflare/meet Index loader that requires a username and returns user information and directory URL. ```APIDOC ## [GET] / (index) loader ### Description Index loader that requires a username and returns user information and directory URL. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **username** (string) - The authenticated username. - **usedAccess** (boolean) - Whether the request had the Cf-Access header. - **directoryUrl** (string) - The user directory URL. ``` -------------------------------- ### History usage example Source: https://github.com/cloudflare/meet Creates a History instance with limit 100, listens for 'logentry' events, and logs an SDP object. The event detail is not populated; listeners read entries. ```ts const log = new History<{ sdp: string }>(100) log.addEventListener('logentry', (e) => { console.log('latest entry:', log.entries.at(-1)) }) log.log({ sdp: offerSdp }) ``` -------------------------------- ### GET /api/debugInfo Source: https://github.com/cloudflare/meet Retrieves stored debug information by UUID. Returns the raw JSON stored in KV storage. ```APIDOC ## [GET] /api/debugInfo ### Description Retrieves stored debug information by UUID. Returns the raw JSON stored in KV storage. ### Method GET ### Endpoint /api/debugInfo?id= ### Parameters #### Query Parameters - **id** (string) - Required - UUID of the debug report ### Response #### Success Response (200) Returns the stored raw JSON with Content-Type: application/json. ``` -------------------------------- ### onStart() lifecycle hook signature Source: https://github.com/cloudflare/meet Lifecycle hook called when the Durable Object (re)starts. Re-initializes this.db from getDb(this) and logs the current meetingId. ```ts async onStart(): Promise ``` -------------------------------- ### useE2eeStatus usage example Source: https://github.com/cloudflare/meet Shows how to call useE2eeStatus with the E2EE group state and participant IDs, and how to access hiddenMembers. ```ts const e2ee = useE2eeStatus(e2eeGroupState, [room.websocket.id, ...room.otherUsers.map((u) => u.id)]) // e2ee?.hiddenMembers — MLS group members the server is not listing ``` -------------------------------- ### GET /parties/rooms/:roomName/* Source: https://github.com/cloudflare/meet Returns a 404 'Not found' response when the PartyKit router returns nothing. This is a route guard for the PartyKit room endpoint. ```APIDOC ## [GET] /parties/rooms/:roomName/* ### Description Returns a 404 'Not found' response when the PartyKit router returns nothing. This is a route guard for the PartyKit room endpoint. ### Method GET ### Endpoint /parties/rooms/:roomName/* ### Parameters #### Path Parameters - **roomName** (string) - Required - The name of the room. ### Response #### Success Response (404) - **body** (string) - `'Not found'` ### Error Handling - **404 'Not found'** - Returned when the PartyKit router returns nothing. ``` -------------------------------- ### Using useRoom to send userUpdate Source: https://github.com/cloudflare/meet Example of using the useRoom hook and sending a userUpdate message via the websocket in a useEffect. ```ts const room = useRoom({ roomName, userMedia }) useEffect(() => { room.websocket.send(JSON.stringify({ type: 'userUpdate', user: myUser })) }, [room.websocket]) ``` -------------------------------- ### Complete AI handshake with requestOpenAIService Source: https://github.com/cloudflare/meet Example usage from ChatRoom.onMessage 'enableAi' that calls requestOpenAIService with the session description, OPENAI_API_TOKEN, OPENAI_MODEL_ENDPOINT, and params. Catches errors, logs 'OpenAI rejected the offer', rethrows, then renegotiates the session with the answer. ```ts // Complete the AI handshake (from ChatRoom.onMessage 'enableAi') const openaiAnswer = await requestOpenAIService( openAiTracksResponse.sessionDescription, env.OPENAI_API_TOKEN, env.OPENAI_MODEL_ENDPOINT, params ).catch((err) => { console.error('OpenAI rejected the offer', err) throw err }) const renegotiationResponse = await openAiSession.Renegotiate(openaiAnswer) ``` -------------------------------- ### GET /parties/rooms/:roomName/* Source: https://github.com/cloudflare/meet Returns a 401 empty response when the getUsername function returns null. This is a route guard for the PartyKit room endpoint. ```APIDOC ## [GET] /parties/rooms/:roomName/* ### Description Returns a 401 empty response when the getUsername function returns null. This is a route guard for the PartyKit room endpoint. ### Method GET ### Endpoint /parties/rooms/:roomName/* ### Parameters #### Path Parameters - **roomName** (string) - Required - The name of the room. ### Response #### Success Response (401) - **body** (empty) - Empty response body. ### Error Handling - **401 (empty)** - Returned when `getUsername` returns null. ``` -------------------------------- ### GET /api/debugInfo Source: https://github.com/cloudflare/meet Returns a 400 'missing id param' response when the id query parameter is not provided. This endpoint is used to retrieve debug information. ```APIDOC ## [GET] /api/debugInfo ### Description Returns a 400 'missing id param' response when the id query parameter is not provided. This endpoint is used to retrieve debug information. ### Method GET ### Endpoint /api/debugInfo ### Parameters #### Query Parameters - **id** (string) - Required - The identifier for the debug report. ### Response #### Success Response (400) - **body** (string) - `'missing id param'` ### Error Handling - **400 'missing id param'** - Returned when the `id` query parameter is missing. ``` -------------------------------- ### BulkRequestDispatcher usage example Source: https://github.com/cloudflare/meet Shows how to use BulkRequestDispatcher to batch multiple calls into a single bulk request dispatched at the end of the current tick. ```ts const dispatcher = new BulkRequestDispatcher<{ id: string }, Map>(64) // Both calls land in the same bulk request, dispatched at end of this tick const first = dispatcher.doBulkRequest({ id: 'a' }, fetchByIds) const second = dispatcher.doBulkRequest({ id: 'b' }, fetchByIds) const map = await first // single fetchByIds(['a', 'b']) call ``` -------------------------------- ### initLogging function signature Source: https://github.com/cloudflare/meet Exported to JavaScript via wasm-bindgen. Initializes console_log at Level::Info and installs the console_error_panic_hook. Called once by worker.js after the WASM module loads. No arguments, returns nothing. ```rust #[wasm_bindgen] #[allow(non_snake_case)] pub fn initLogging() ``` -------------------------------- ### Ewma usage example Source: https://github.com/cloudflare/meet Creates an Ewma estimator with a half-life of 2000 ms and a clock using performance.now(). Inserts a value and retrieves the smoothed value in bits/s. ```ts import Ewma from '~/utils/ewma' const estimator = new Ewma(2000, 0, { now: () => performance.now() }) estimator.insert(1_200_000) const avg = estimator.value() // smoothed value in bits/s ``` -------------------------------- ### Deploy the application Source: https://github.com/cloudflare/meet/blob/main/README.md Run the deploy script to deploy the application to Cloudflare. ```sh npm run deploy ``` -------------------------------- ### FIFOScheduler Source: https://github.com/cloudflare/meet A serializer that runs tasks in FIFO order, ensuring each task completes before the next starts. Use schedule() to enqueue a task and get a promise for its result. ```APIDOC ## FIFOScheduler ### Description A serializer that runs every task to completion in FIFO order, regardless of the order in which schedule is called relative to task completion. Each call returns a promise that resolves with the task's value or rejects with its error. ### Constructor `constructor()` ### Methods #### schedule(task: Task): Promise - **task** (() => Promise) - Required - The task to run. ### Example ```ts const scheduler = new FIFOScheduler() // These run strictly one after another, in call order const a = await scheduler.schedule(async () => readState()) const b = await scheduler.schedule(async () => updateState(a)) ``` ``` -------------------------------- ### safetyNumberToAlphanumeric usage example Source: https://github.com/cloudflare/meet Example call to safetyNumberToAlphanumeric with a hash buffer and length 20. ```ts const sn = safetyNumberToAlphanumeric(hashBuffer, 20) // e.g. "1K2M3P4Q5R6S7T8V9WA0" (18 of the 20 chars shown for brevity) ``` -------------------------------- ### useUserMedia({ micDeviceId, cameraDeviceId }) Source: https://github.com/cloudflare/meet Hook to access user media devices. Both parameters are optional; devices are auto-picked if not provided. ```APIDOC ## Hook: useUserMedia({ micDeviceId, cameraDeviceId }) ### Description Hook to access user media devices. Both parameters are optional; devices are auto-picked if not provided. ### Parameters - `micDeviceId` (string) - Optional - Microphone device ID. - `cameraDeviceId` (string) - Optional - Camera device ID. ``` -------------------------------- ### POST / Source: https://github.com/cloudflare/meet Root action that reads a form field 'room' and joins a room, redirecting to the room URL. Throws an invariant if the room is not a string. ```APIDOC ## [POST] / ### Description Root action that reads a form field 'room' and joins a room, redirecting to the room URL. Throws an invariant if the room is not a string. ### Method POST ### Endpoint / ### Parameters #### Request Body - **room** (string) - Required - The room name to join. ### Response #### Redirect (302) - Redirects to `/{room.replace(/ /g, '-')}`. ``` -------------------------------- ### new BulkRequestDispatcher(batchSizeLimit) Source: https://github.com/cloudflare/meet Constructor for a bulk request dispatcher with a batch size limit. ```APIDOC ## Constructor: new BulkRequestDispatcher(batchSizeLimit) ### Description Constructor for a bulk request dispatcher with a batch size limit. ### Parameters - `batchSizeLimit` (number) - Required - Default: `64` - Maximum batch size. ``` -------------------------------- ### dispose() method and usage example Source: https://github.com/cloudflare/meet The dispose() method terminates the worker. The usage example shows creating an EncryptionWorker with id and safetyNumberLength, calling initializeAndCreateGroup(), and disposing in a finally block. ```TypeScript dispose() { this.worker.terminate() } ``` ```TypeScript const enc = new EncryptionWorker({ id: ws.id, safetyNumberLength: 20 }) try { enc.initializeAndCreateGroup() // ... media encryption is set up via setupSenderTransform / setupReceiverTransform } finally { enc.dispose() } ``` -------------------------------- ### useCopyToClipboard(delay) Source: https://github.com/cloudflare/meet Hook to copy text to clipboard with a delay. The delay is in milliseconds. ```APIDOC ## Hook: useCopyToClipboard(delay) ### Description Hook to copy text to clipboard with a delay. The delay is in milliseconds. ### Parameters - `delay` (number) - Required - Delay in milliseconds before copying. ``` -------------------------------- ### Set up .dev.vars with Calls App ID and Secret Source: https://github.com/cloudflare/meet/blob/main/README.md Required variables for local development. Replace placeholders with your actual Calls App ID and secret from the Cloudflare Realtime dashboard. ```plaintext CALLS_APP_ID= CALLS_APP_SECRET= ``` -------------------------------- ### useE2EE({ enabled, room, partyTracks, safetyNumberLength }) Source: https://github.com/cloudflare/meet Hook for enabling end-to-end encryption in a meeting. Options include enabled, safetyNumberLength, partyTracks, and room. ```APIDOC ## Hook: useE2EE({ enabled, room, partyTracks, safetyNumberLength }) ### Description Hook for enabling end-to-end encryption in a meeting. Options include enabled, safetyNumberLength, partyTracks, and room. ### Parameters - `enabled` (boolean) - Optional - Default: `false` - Whether E2EE is enabled. - `safetyNumberLength` (number) - Optional - Default: `20` - Length of the safety number. - `partyTracks` (PartyTracks) - Required - Party tracks object. - `room` (type not specified) - Required - The room identifier. ``` -------------------------------- ### initialize() and initializeAndCreateGroup() method signatures Source: https://github.com/cloudflare/meet initialize() posts { type: 'initialize', id, safetyNumberLength } and is used by non-creator users. initializeAndCreateGroup() posts { type: 'initializeAndCreateGroup', id, safetyNumberLength } and is used only by the first user in the room to create the MLS group. ```TypeScript initialize() // posts { type: 'initialize', id, safetyNumberLength } initializeAndCreateGroup() // posts { type: 'initializeAndCreateGroup', id, safetyNumberLength } ``` -------------------------------- ### queue (consumer) Source: https://github.com/cloudflare/meet Consumer queue with configuration options for batch size and timeout. ```APIDOC ## Consumer: queue ### Description Consumer queue with configuration options for batch size and timeout. ### Parameters - `max_batch_size` (number) - Optional - Default: `10` - Maximum batch size. - `max_batch_timeout` (number) - Optional - Default: `5` - Maximum batch timeout. ``` -------------------------------- ### new Ewma(halfLifeMs, initialValue, clock?) Source: https://github.com/cloudflare/meet Constructor for an Exponential Weighted Moving Average (EWMA) with a half-life and initial value. ```APIDOC ## Constructor: new Ewma(halfLifeMs, initialValue, clock?) ### Description Constructor for an Exponential Weighted Moving Average (EWMA) with a half-life and initial value. ### Parameters - `halfLifeMs` (number) - Required - Half-life in milliseconds. - `initialValue` (type not specified) - Required - Initial value. - `clock` (object) - Optional - Default: `Date` - Clock object with `now()` method. ``` -------------------------------- ### usePeerConnection(config: PartyTracksConfig) Source: https://github.com/cloudflare/meet Hook for managing a peer connection. Accepts a configuration object with apiExtraParams, iceServers, and maxApiHistory. ```APIDOC ## Hook: usePeerConnection(config: PartyTracksConfig) ### Description Hook for managing a peer connection. Accepts a configuration object with apiExtraParams, iceServers, and maxApiHistory. ### Parameters - `apiExtraParams` (type not specified) - Optional - Extra API parameters. - `iceServers` (type not specified) - Optional - ICE servers configuration. - `maxApiHistory` (number) - Optional - Default: `100` - Maximum API history length. ``` -------------------------------- ### POST /v1/turn/keys/{TURN_SERVICE_ID}/credentials/generate-ice-servers Source: https://github.com/cloudflare/meet Generates TURN ICE server credentials. Returns a list of ICE servers. ```APIDOC ## POST /v1/turn/keys/{TURN_SERVICE_ID}/credentials/generate-ice-servers ### Description Generates TURN ICE server credentials. Returns a list of ICE servers. ### Method POST ### Endpoint `https://rtc.live.cloudflare.com/v1/turn/keys/{TURN_SERVICE_ID}/credentials/generate-ice-servers` ### Parameters #### Path Parameters - **TURN_SERVICE_ID** (string) - Required - The TURN service ID. #### Request Body - **ttl** (integer) - Required - Time-to-live in seconds (e.g., 86400). ### Response #### Success Response (200) - **iceServers** (RTCIceServer[]) - The list of ICE servers. ### Errors Non-2xx responses indicate an error. ``` -------------------------------- ### usePeerConnection return type Source: https://github.com/cloudflare/meet The return type of usePeerConnection. iceConnectionState starts as 'new' and tracks iceconnectionstatechange events. ```ts { partyTracks: PartyTracks, iceConnectionState: RTCIceConnectionState } ``` -------------------------------- ### Create a session with external WebRTC peer Source: https://github.com/cloudflare/meet Creates a session that relays between the room and an external WebRTC server (e.g., OpenAI). Uses the thirdparty flag set to true and then creates a new audio track. ```ts // Create a session that will relay between the room and an external WebRTC server const session = await CallsNewSession( env.CALLS_APP_ID, env.CALLS_APP_SECRET, env.API_EXTRA_PARAMS, await room.getMeetingId(), true // thirdparty: connect an external peer ) const tracks = await session.NewTracks({ tracks: [{ location: 'local', trackName: 'ai-generated-voice', kind: 'audio' }], }) ``` -------------------------------- ### POST {OPENAI_MODEL_ENDPOINT} Source: https://github.com/cloudflare/meet Sends an SDP offer to the OpenAI Realtime API and receives an SDP answer. ```APIDOC ## POST {OPENAI_MODEL_ENDPOINT} ### Description Sends an SDP offer to the OpenAI Realtime API and receives an SDP answer. ### Method POST ### Endpoint `{OPENAI_MODEL_ENDPOINT}?{voice,instructions,model}` ### Parameters #### Query Parameters - **voice** (string) - Required - Voice selection. - **instructions** (string) - Required - Instructions for the model. - **model** (string) - Optional - Model identifier, default is `gpt-4o-realtime-preview-2024-10-01`. #### Request Body - **body** (string) - Required - The SDP offer from Calls. ### Response #### Success Response (200) - **body** (string) - The SDP answer text (`application/sdp`). ### Errors Non-2xx responses indicate an error. ``` -------------------------------- ### getIceServers server helper Source: https://github.com/cloudflare/meet Returns undefined when either TURN_SERVICE_ID or TURN_SERVICE_TOKEN is missing; otherwise POSTs { ttl: 86400 } to the Cloudflare TURN credentials endpoint and returns the iceServers array from the JSON response. ```typescript export async function getIceServers({ TURN_SERVICE_ID, TURN_SERVICE_TOKEN, }: Env): Promise ``` -------------------------------- ### Using blurVideoTrack with camera.addTransform Source: https://github.com/cloudflare/meet Shows how to enable and disable background blur on a camera track using the blurVideoTrack transform. The import path is '~/utils/blurVideoTrack'. ```ts import blurVideoTrack from '~/utils/blurVideoTrack' camera.addTransform(blurVideoTrack) // enable background blur camera.removeTransform(blurVideoTrack) ``` -------------------------------- ### GET /:roomName/room Source: https://github.com/cloudflare/meet Joined room loader that requires a username and returns various configuration flags. Redirects unjoined users back to the lobby. ```APIDOC ## [GET] /:roomName/room ### Description Joined room loader that requires a username and returns various configuration flags. Redirects unjoined users back to the lobby. ### Method GET ### Endpoint /:roomName/room ### Parameters #### Path Parameters - **roomName** (string) - Required - The room name. ### Response #### Success Response (200) - **username** (string) - The authenticated username. - **bugReportsEnabled** (boolean) - Whether bug reports are enabled. - **disableLobbyEnforcement** (boolean) - Whether lobby enforcement is disabled. - **mode** (string) - The mode (e.g., development). - **hasDb** (boolean) - Whether a database is available. - **hasAiCredentials** (boolean) - Whether AI credentials are available. - **dashboardDebugLogsBaseUrl** (string) - Base URL for dashboard debug logs. #### Redirect (302) - Redirects back to the lobby if the user is not joined and lobby enforcement is enabled. ``` -------------------------------- ### Throw platform-unsupported error in setupSenderTransform/setupReceiverTransform Source: https://github.com/cloudflare/meet Thrown when the browser supports neither Firefox's RTCRtpScriptTransform nor Chrome's createEncodedStreams. Catch around the async calls; the errors are rejected promises. ```ts throw new Error( 'Neither RTCRtpScriptTransform nor RTCRtpSender.createEncodedStreams methods supported' ) // and the RTCRtpReceiver variant in setupReceiverTransform ``` -------------------------------- ### Session — createCookieSessionStorage with __session cookie Source: https://github.com/cloudflare/meet Creates a Remix cookie session storage with cookie name `__session`. Exports `getSession(cookieHeader)`, `commitSession(session)`, `destroySession(session)`. The session only holds the `username` key. `sameSite: true` relies on Cloudflare Access for production auth; the hardcoded `secrets` array is exactly as written in source and should not be reused in your own deployments. ```ts export const { getSession, commitSession, destroySession } = createCookieSessionStorage({ cookie: { name: '__session', secrets: ['oooOOooOOoOOoOOOOoo'], sameSite: true, httpOnly: true, }, }) ``` -------------------------------- ### useMediaDevices(filter?) Source: https://github.com/cloudflare/meet Hook to list media devices with an optional filter function. ```APIDOC ## Hook: useMediaDevices(filter?) ### Description Hook to list media devices with an optional filter function. ### Parameters - `filter` (function) - Optional - Default: `() => true` - Filter function for MediaDeviceInfo. ``` -------------------------------- ### GET /partytracks/* Source: https://github.com/cloudflare/meet Proxies the browser's partytracks client to Cloudflare Calls, forwarding Calls API calls with the app secret added server-side. ```APIDOC ## [GET] /partytracks/* ### Description Proxies the browser's partytracks client to Cloudflare Calls, forwarding Calls API calls with the app secret added server-side. ### Method GET ### Endpoint /partytracks/* ### Response #### Success Response (200) - Returns whatever `routePartyTracksRequest` returns. ``` -------------------------------- ### GET /:roomName Source: https://github.com/cloudflare/meet Lobby loader that requires a username and returns the Calls App ID. Also fires a reportRefresh event once per browser session. ```APIDOC ## [GET] /:roomName ### Description Lobby loader that requires a username and returns the Calls App ID. Also fires a reportRefresh event once per browser session. ### Method GET ### Endpoint /:roomName ### Parameters #### Path Parameters - **roomName** (string) - Required - The room name. ### Response #### Success Response (200) - **username** (string) - The authenticated username. - **callsAppId** (string) - The Calls App ID from environment. ``` -------------------------------- ### loadWorker(handleEvents) Source: https://github.com/cloudflare/meet Creates a new E2EE worker, waits for the workerReady handshake, and installs message/error handlers. Returns the worker augmented with a safePostMessage function. ```APIDOC ## loadWorker(handleEvents) ### Description Creates `new Worker('/e2ee/worker.js')`, waits for the `workerReady` handshake, installs `onmessage`/`onerror` handlers, and returns the worker augmented with `safePostMessage` (two overloads — with and without a `Transferable[]` transfer list). ### Method Function ### Parameters #### Function Parameters - **handleEvents** (function) - Required - Callback receiving `MessagesFromE2eeWorker` messages ### Returns Worker augmented with `safePostMessage` ### Example ```ts import { loadWorker } from './e2ee' const worker = await loadWorker((message) => { console.log('Message from worker:', message) }) ``` ``` -------------------------------- ### GET /parties/rooms/:roomName/* Source: https://github.com/cloudflare/meet PartyServer routing that requires authentication, delegates to routePartykitRequest, and handles WebSocket upgrades. Returns 401 when unauthenticated and 404 when the party router returns nothing. ```APIDOC ## [GET] /parties/rooms/:roomName/* ### Description PartyServer routing that requires authentication, delegates to routePartykitRequest, and handles WebSocket upgrades. Returns 401 when unauthenticated and 404 when the party router returns nothing. ### Method GET ### Endpoint /parties/rooms/:roomName/* ### Parameters #### Path Parameters - **roomName** (string) - Required - The room name. ### Response #### Success Response (200) - Returns the party response from `routePartykitRequest`. #### Error Response (401) - Empty body when unauthenticated. #### Error Response (404) - 'Not found' when the party router returns nothing. ``` -------------------------------- ### Schema — getDb function Source: https://github.com/cloudflare/meet Returns a Drizzle `D1Database` client for `context.env.DB`, or `null` when the `DB` binding is absent. Note D1 column names match Drizzle field names (e.g., `userCount`, `created`, `modified`, `deleted`). ```ts export function getDb(context: { env: Env }) { if (!context.env.DB) { return null } return drizzle(context.env.DB) } ``` -------------------------------- ### useUserMetadata interface and hook signature Source: https://github.com/cloudflare/meet react-query useQuery keyed on {userDirectoryUrl}?{email}. When userDirectoryUrl is set, fetches it with credentials: 'include'; if the response is JSON, returns { ...parsedData, displayName: `${firstName} ${lastName}` }. Otherwise (or without a directory URL) returns initialData = { displayName: email }. ```ts interface UserMetadata { displayName: string firstName?: string lastName?: string timeZone?: string photob64?: string } export function useUserMetadata(email: string) ``` -------------------------------- ### remixHandler: createRequestHandler wrapper Source: https://github.com/cloudflare/meet Creates a single Remix request handler from the pre-built build and mode, then wraps it to augment the app load context with the current mode. Used by the worker's fetch entry point. ```ts const baseRemixHandler = createRequestHandler(build, mode) export const remixHandler = (request: Request, env: AppLoadContext) => { return baseRemixHandler(request, { ...env, mode }) } ``` -------------------------------- ### Mode — resolve NODE_ENV to Mode type Source: https://github.com/cloudflare/meet Defines `Mode` as `'production' | 'development' | 'test'` and resolves `mode` once at build time from `process.env.NODE_ENV`. Throws via `invariant` if `NODE_ENV` is not one of the three modes. `mode` is injected into every Remix `AppLoadContext`. ```ts const modes = ['production', 'development', 'test'] as const export type Mode = (typeof modes)[number] const NODE_ENV = process.env.NODE_ENV const foundMode = modes.find((m) => m === NODE_ENV) invariant(foundMode) export const mode = foundMode ``` -------------------------------- ### safeRedirect utility Source: https://github.com/cloudflare/meet Returns redirect(url, init) but sanitizes javascript:, data:, and vbscript: (after decoding/trimming/lowercasing) to '/', guarding against open-redirect injection. ```typescript export function safeRedirect(url: string, init?: number | ResponseInit) ``` -------------------------------- ### new History(limit) Source: https://github.com/cloudflare/meet Constructor for a history buffer with a limit. The limit is clamped to at least 1. ```APIDOC ## Constructor: new History(limit) ### Description Constructor for a history buffer with a limit. The limit is clamped to at least 1. ### Parameters - `limit` (number) - Required - Default: `Infinity` - Maximum history length (clamped to ≥ 1). ``` -------------------------------- ### onNewSafetyNumber(handler) method signature and usage Source: https://github.com/cloudflare/meet Registers a handler for worker newSafetyNumber events. The usage example shows setting group state with the safety number converted to alphanumeric and the members list. ```TypeScript onNewSafetyNumber( handler: (safetyNumber: Uint8Array, members: string[]) => void ) ``` ```TypeScript encryptionWorker.onNewSafetyNumber((hash, members) => { setGroupState({ safetyNumber: safetyNumberToAlphanumeric(hash, 20), members, }) }) ``` -------------------------------- ### Schema — table definitions (AnalyticsRefreshes, AnalyticsSimpleCallFeedback, Meetings) Source: https://github.com/cloudflare/meet Defines three D1 tables: `AnalyticsRefreshes` (version), `AnalyticsSimpleCallFeedback` (version, experiencedIssues, meetingId FK to Meetings), and `Meetings` (id PK, peakUserCount, ended). Written by various endpoints and ChatRoom methods. ```ts export const AnalyticsRefreshes = sqliteTable('AnalyticsRefreshes', { ...metadataColumns, version: text('version').notNull(), }) export const AnalyticsSimpleCallFeedback = sqliteTable( 'AnalyticsSimpleCallFeedback', { ...metadataColumns, version: text('version').notNull(), experiencedIssues: integer('experiencedIssues').notNull(), meetingId: text('meetingId').references(() => Meetings.id), } ) export const Meetings = sqliteTable('Meetings', { ...metadataColumns, id: text('id').primaryKey(), peakUserCount: integer('userCount').notNull(), ended: text('ended'), }) ``` -------------------------------- ### loadWorker(handleEvents) function signature Source: https://github.com/cloudflare/meet Defines the loadWorker function that creates a new Worker('/e2ee/worker.js'), waits for the workerReady handshake, installs onmessage/onerror handlers, and returns the worker augmented with safePostMessage. The returned object is Object.assign(worker, { safePostMessage }). ```TypeScript export async function loadWorker( handleEvents: (message: MessagesFromE2eeWorker) => void ) ``` -------------------------------- ### AppLoadContext augmentation for Remix Cloudflare Source: https://github.com/cloudflare/meet Augments the AppLoadContext interface from @remix-run/cloudflare to include env and mode properties. Every Remix loader/action receives context.env: Env and context.mode: Mode. ```ts declare module '@remix-run/cloudflare' { export interface AppLoadContext { env: Env mode: Mode } } ``` -------------------------------- ### BulkRequestDispatcher Source: https://github.com/cloudflare/meet Collects entries during the current event-loop iteration and dispatches them together in a macrotask, so multiple callers in the same tick share one bulk request. Use doBulkRequest() to add an entry and get a promise for the bulk response. ```APIDOC ## BulkRequestDispatcher ### Description Collects entries during the current event-loop iteration and dispatches them together in a macrotask (setTimeout(..., 0)), so multiple callers in the same tick share one bulk request. ### Constructor `constructor(batchSizeLimit: number = DefaultBatchSizeLimit)` - **batchSizeLimit** (number) - Optional - Default is 64. When the accumulated batch reaches this limit, the batch and its pending response are reset so the next call starts a fresh bulk request. ### Methods #### doBulkRequest(params: RequestEntryParams, bulkRequestFunc: (bulkCopy: RequestEntryParams[]) => Promise): Promise - **params** (RequestEntryParams) - Required - The entry to add to the current batch. - **bulkRequestFunc** ((bulkCopy: RequestEntryParams[]) => Promise) - Required - The function to execute the bulk request with the batch copy. ### Behavior - Resets the batch/response pair if the limit has been reached. - Pushes params onto the batch; if a bulk request promise already exists for the current iteration, returns that same promise (all callers resolve/reject with the one bulk response). - Otherwise creates a promise and schedules bulkRequestFunc(batchCopy) on the macrotask queue (batchCopy = batch.splice(0, batch.length)). The stored promise is cleared before invoking bulkRequestFunc, so callers arriving after the flush get a new batch. ### Example ```ts const dispatcher = new BulkRequestDispatcher<{ id: string }, Map>(64) // Both calls land in the same bulk request, dispatched at end of this tick const first = dispatcher.doBulkRequest({ id: 'a' }, fetchByIds) const second = dispatcher.doBulkRequest({ id: 'b' }, fetchByIds) const map = await first // single fetchByIds(['a', 'b']) call ``` ``` -------------------------------- ### dashboardLogsLink utility Source: https://github.com/cloudflare/meet Builds {baseUrl}/observability/logs?view=events&needle=...&filters=..., URL-encoding the filter array. ```typescript export function dashboardLogsLink( baseUrl: string, filters: { id: string; type: string; key: string; value: string; operation: 'eq' }[] ) ``` -------------------------------- ### useCopyToClipboard Source: https://github.com/cloudflare/meet Returns a tuple with a `copied` boolean and a `copy` function. The `copy` function writes a value to the clipboard and temporarily sets `copied` to true for a specified delay. ```APIDOC ## useCopyToClipboard ### Description Returns `[copied, copy] as const`. `copy(value: string)` writes to `navigator.clipboard`, sets `copied = true`, and resets it after `delay` ms (cleared on unmount). ### Signature ```ts export default function useCopyToClipboard(delay = 2000) ``` ### Parameters - `delay` (number) - Optional - The duration in milliseconds to keep `copied` true. Defaults to 2000. ### Returns - `copied` (boolean) - Whether the copy operation was recently performed. - `copy` (function) - A function that takes a string value and copies it to the clipboard. ### Example ```ts const [copied, copy] = useCopyToClipboard() ``` ``` -------------------------------- ### EncryptionWorker class definition Source: https://github.com/cloudflare/meet Defines the EncryptionWorker class with properties and constructor. The constructor takes a config object with id and safetyNumberLength (16–52). Creates a new Worker('/e2ee/worker.js') immediately. The get worker() throws an error if _worker is null. ```TypeScript export class EncryptionWorker { get worker(): Worker _worker: Worker | null = null safetyNumber: number = -1 id: string safetyNumberLength: number constructor(config: { id: string; safetyNumberLength: number }) } ``` -------------------------------- ### mic, camera, screenshare Source: https://github.com/cloudflare/meet Module-scope exports for the default microphone, camera, and screenshare media sources. These are configured with default constraints and broadcasting settings. ```APIDOC ## mic, camera, screenshare ### Description Module-scope exports for the default microphone, camera, and screenshare media sources. These are configured with default constraints and broadcasting settings. ### Definition ```ts export const mic = getMic({ broadcasting: broadcastByDefault }) // broadcasting = mode === 'production' export const camera = getCamera({ broadcasting: true, constraints: { width: { ideal: 1280 }, height: { ideal: 720 } } }) export const screenshare = getScreenshare({ audio: false }) ``` ``` -------------------------------- ### onConnect(connection, ctx) method signature Source: https://github.com/cloudflare/meet Handles a new WebSocket connection. Starts a 15s alarm if none is scheduled, resolves the username via getUsername(ctx.request), and throws if no authenticated identity. Restores or creates the user record, records heartbeat, and calls trackPeakUserCount() and broadcastRoomState(). ```ts async onConnect( connection: Connection, ctx: ConnectionContext ): Promise ```