mirror of
https://github.com/tauri-apps/plugins-workspace.git
synced 2026-09-22 21:30:44 +02:00
chore: update documentation
This commit is contained in:
@@ -2,8 +2,17 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/**
|
||||
* Open a WebSocket connection using a Rust client in JS.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
import { invoke, Channel } from '@tauri-apps/api/core'
|
||||
|
||||
/**
|
||||
* Configuration used to open a WebSocket connection, forwarded to the underlying `tungstenite` client.
|
||||
*/
|
||||
export interface ConnectionConfig {
|
||||
/**
|
||||
* Read buffer capacity. The default value is 128 KiB.
|
||||
@@ -39,16 +48,29 @@ export interface ConnectionConfig {
|
||||
headers?: HeadersInit
|
||||
}
|
||||
|
||||
/**
|
||||
* A tagged WebSocket message, discriminated by its `type` field.
|
||||
*/
|
||||
export interface MessageKind<T, D> {
|
||||
/** The kind of message, e.g. `'Text'`, `'Binary'`, `'Ping'`, `'Pong'` or `'Close'`. */
|
||||
type: T
|
||||
/** The message payload, whose shape depends on {@link MessageKind.type}. */
|
||||
data: D
|
||||
}
|
||||
|
||||
/**
|
||||
* The code and reason sent (or received) when a WebSocket connection is closed.
|
||||
*/
|
||||
export interface CloseFrame {
|
||||
/** The WebSocket close status code, e.g. `1000` for a normal closure. */
|
||||
code: number
|
||||
/** A human-readable explanation for why the connection was closed. */
|
||||
reason: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A message sent to or received from a WebSocket connection.
|
||||
*/
|
||||
export type Message =
|
||||
| MessageKind<'Text', string>
|
||||
| MessageKind<'Binary', number[]>
|
||||
@@ -56,15 +78,52 @@ export type Message =
|
||||
| MessageKind<'Pong', number[]>
|
||||
| MessageKind<'Close', CloseFrame | null>
|
||||
|
||||
/**
|
||||
* A WebSocket connection, created with {@link WebSocket.connect}.
|
||||
*
|
||||
* @since 2.0.0
|
||||
*/
|
||||
export default class WebSocket {
|
||||
/** The identifier of the underlying connection managed by the Rust side. */
|
||||
id: number
|
||||
private readonly listeners: Set<(arg: Message) => void>
|
||||
|
||||
/**
|
||||
* Creates a {@link WebSocket} wrapper around an already-open connection.
|
||||
*
|
||||
* This is used internally by {@link WebSocket.connect}; use that instead of calling this
|
||||
* constructor directly.
|
||||
*
|
||||
* @param id The identifier of the connection returned by the Rust side.
|
||||
* @param listeners The set of callbacks to notify when a message is received.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import WebSocket from '@tauri-apps/plugin-websocket';
|
||||
*
|
||||
* // internally used by `WebSocket.connect`; prefer calling that instead
|
||||
* const ws = await WebSocket.connect('wss://example.com');
|
||||
* ```
|
||||
*/
|
||||
constructor(id: number, listeners: Set<(arg: Message) => void>) {
|
||||
this.id = id
|
||||
this.listeners = listeners
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a WebSocket connection to the given URL.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import WebSocket from '@tauri-apps/plugin-websocket';
|
||||
*
|
||||
* const ws = await WebSocket.connect('wss://example.com');
|
||||
* ```
|
||||
*
|
||||
* @param url The URL to connect to, e.g. `ws://` or `wss://` (the latter requires one of the
|
||||
* plugin's TLS Cargo features to be enabled).
|
||||
* @param config Configuration forwarded to the underlying `tungstenite` client.
|
||||
* @returns A promise resolving to the connected {@link WebSocket}.
|
||||
* @since 2.0.0
|
||||
*/
|
||||
static async connect(
|
||||
url: string,
|
||||
config?: ConnectionConfig
|
||||
@@ -89,6 +148,20 @@ export default class WebSocket {
|
||||
}).then((id) => new WebSocket(id, listeners))
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a listener that is called whenever a message is received on this connection, including
|
||||
* an error message (as a `'Close'` message) when the underlying stream fails.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import WebSocket from '@tauri-apps/plugin-websocket';
|
||||
*
|
||||
* const ws = await WebSocket.connect('wss://example.com');
|
||||
* const unlisten = ws.addListener((message) => console.log(message));
|
||||
* ```
|
||||
*
|
||||
* @param cb The callback invoked with each received {@link Message}.
|
||||
* @returns A function that removes the listener when called.
|
||||
*/
|
||||
addListener(cb: (arg: Message) => void): () => void {
|
||||
this.listeners.add(cb)
|
||||
|
||||
@@ -97,6 +170,22 @@ export default class WebSocket {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message through the WebSocket connection.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import WebSocket from '@tauri-apps/plugin-websocket';
|
||||
*
|
||||
* const ws = await WebSocket.connect('wss://example.com');
|
||||
* await ws.send('Hello World');
|
||||
* await ws.send([1, 2, 3]);
|
||||
* await ws.send({ type: 'Text', data: 'Hello World' });
|
||||
* ```
|
||||
*
|
||||
* @param message The message to send: a plain string (sent as a `'Text'` message), a numeric
|
||||
* array (sent as a `'Binary'` message), or an explicit {@link Message} object.
|
||||
* @returns A promise resolving when the message has been sent.
|
||||
*/
|
||||
async send(message: Message | string | number[]): Promise<void> {
|
||||
let m: Message
|
||||
if (typeof message === 'string') {
|
||||
@@ -116,6 +205,16 @@ export default class WebSocket {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the WebSocket connection, sending a normal closure (`1000`) close frame to the server.
|
||||
* @example
|
||||
* ```typescript
|
||||
* import WebSocket from '@tauri-apps/plugin-websocket';
|
||||
*
|
||||
* const ws = await WebSocket.connect('wss://example.com');
|
||||
* await ws.disconnect();
|
||||
* ```
|
||||
*/
|
||||
async disconnect(): Promise<void> {
|
||||
await this.send({
|
||||
type: 'Close',
|
||||
|
||||
@@ -274,27 +274,36 @@ async fn send(
|
||||
}
|
||||
}
|
||||
|
||||
/// Initializes the plugin with the default [`Builder`], i.e. without a custom TLS [`Connector`].
|
||||
pub fn init<R: Runtime>() -> TauriPlugin<R> {
|
||||
Builder::default().build()
|
||||
}
|
||||
|
||||
/// Builder for the WebSocket plugin, used to configure a custom TLS [`Connector`] before calling [`Builder::build`].
|
||||
#[derive(Default)]
|
||||
pub struct Builder {
|
||||
tls_connector: Option<Connector>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
/// Creates a new [`Builder`] with no custom TLS [`Connector`] configured.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
tls_connector: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the TLS [`Connector`] used to establish `wss://` connections.
|
||||
///
|
||||
/// When this is not called (or is called with [`Connector::Plain`]) and a `rustls-tls` or
|
||||
/// `rustls-tls-native-roots` feature is enabled, [`Builder::build`] installs `rustls`'s `ring`
|
||||
/// crypto provider as the process default if none is installed yet.
|
||||
pub fn tls_connector(mut self, connector: Connector) -> Self {
|
||||
self.tls_connector.replace(connector);
|
||||
self
|
||||
}
|
||||
|
||||
/// Builds the plugin, registering the `connect` and `send` commands and the shared connection state.
|
||||
pub fn build<R: Runtime>(self) -> TauriPlugin<R> {
|
||||
PluginBuilder::new("websocket")
|
||||
.invoke_handler(tauri::generate_handler![connect, send])
|
||||
|
||||
Reference in New Issue
Block a user