// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // TypeScript surface for the rclnodejs Web Runtime browser SDK. // // Goal: minimum setup. The user supplies one string per call — the // ROS interface name — and the SDK derives the request, response, and // message shapes from rclnodejs's auto-generated MessagesMap / ServicesMap. // // const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( // '/add_two_ints', { a: '2n', b: '40n' } // typed // ); // // const sub = await ros.subscribe<'std_msgs/msg/String'>( // '/scan', (m) => render(m.data) // m.data: string // ); // // Untyped fallbacks (no generic) are kept so capabilities not in the // generated maps still work. declare module 'rclnodejs/web' { // -------- Wire-shape mapping ---------------------------------------- /** Wire encoding of a ROS 2 64-bit integer field. */ export type Int64Wire = `${number}n`; /** * Map an in-process rclnodejs message shape to its on-wire JSON shape. * * The Web Runtime serialises typed arrays as regular JSON arrays. * 64-bit integer fields (`bigint` in the generated types) become * `"n"` strings so they survive `JSON.stringify`. * * Cases (checked in order): * - `bigint` → {@link Int64Wire} (the `"n"` string) * - `ReadonlyArray` → `WireType[]` (recurse per element) * - typed arrays → `WireType[]` * - `Date` → `string` (ISO string on the wire) * - `object` → field-wise recursion * - everything else → passes through unchanged * * @experimental — exposed for advanced consumers that want to derive * wire shapes by hand. Most users should rely on the type-name * generics on {@link RosClient.call} / `subscribe` / etc., which * apply this mapping internally. */ // The bigint check uses `[T] extends [bigint]` (tuple wrapper) instead // of bare `T extends bigint` so the conditional doesn't distribute // across union members like `bigint | string` (which would map only // the bigint half and silently drop the rest). export type WireType = [T] extends [bigint] ? Int64Wire : _WireRecurse; /** Recursion step for {@link WireType}; pulled out to keep the cascade flat. */ type _WireRecurse = T extends | ReadonlyArray | (ArrayBufferView & { readonly [index: number]: infer Element }) ? WireType[] : T extends Date ? string : T extends object ? { [K in keyof T]: WireType } : T; // -------- Type-name lookup helpers ---------------------------------- // The maps below are declared by rclnodejs's own .d.ts files via a // `declare module 'rclnodejs' { type MessagesMap = {...} }` augmentation. // Reaching them across the module boundary requires the inline // `import('rclnodejs')` form — a default-style `import type rclnodejs // from 'rclnodejs'` would resolve to the runtime's *value* export, not // the namespace, and `MessagesMap` would silently collapse to `never`. /** ROS 2 message type names available in the sourced environment. */ export type MessageName = keyof import('rclnodejs').MessagesMap; /** ROS 2 service type names available in the sourced environment. */ export type ServiceName = keyof import('rclnodejs').ServicesMap; /** Wire shape of the named message. `Msg<'std_msgs/msg/String'>` → `{ data: string }`. */ export type Msg = WireType< import('rclnodejs').MessagesMap[TName] >; type _SvcCtor = import('rclnodejs').ServicesMap[TName]; /** Wire shape of the named service request. */ export type SvcReq = WireType< InstanceType<_SvcCtor['Request']> >; /** Wire shape of the named service response. */ export type SvcResp = WireType< InstanceType<_SvcCtor['Response']> >; /** ROS 2 action type names available in the sourced environment. */ export type ActionName = keyof import('rclnodejs').ActionsMap; /** Wire shape of the named action's goal request. */ export type ActionGoal = WireType< import('rclnodejs').ActionGoal >; /** Wire shape of the named action's feedback message. */ export type ActionFeedback = WireType< import('rclnodejs').ActionFeedback >; /** Wire shape of the named action's result. */ export type ActionResult = WireType< import('rclnodejs').ActionResult >; // -------- SDK ------------------------------------------------------ /** * Subscription handle returned by {@link RosClient.subscribe}. * Closing the handle cancels the subscription on the runtime side. */ export interface Subscription { readonly subId: string; close(): Promise; } export type ActionStatus = 'succeeded' | 'canceled' | 'aborted' | 'unknown'; /** * Handle for an in-flight action goal, returned by {@link RosClient.action}. * * HTTP `cancel()` rejects with `unsupported_kind`; use WebSocket to cancel. * Closing an HTTP stream does not cancel its ROS goal. * `result` resolves with the ROS payload even when canceled or aborted; * inspect `status` after awaiting it to determine the outcome. */ export interface ActionHandle { readonly goalId: string; readonly result: Promise; /** Undefined until a terminal response; missing/unrecognized status is 'unknown'. */ readonly status: ActionStatus | undefined; cancel(): Promise; } export interface ConnectOptions { /** * Reopen the WebSocket link with backoff after a drop, replaying * subscriptions. Enables `'reconnecting'` / `'reconnected'` — see * {@link RosClient.on}; `'disconnected'` fires on any unexpected drop * regardless of this option. The first connect attempt still rejects * once rather than retrying forever. * @default false */ reconnect?: boolean; } /** Detail passed to a `'reconnecting'` listener. */ export interface ReconnectingDetail { /** 1-based attempt number for this reconnect sequence. */ attempt: number; /** Delay in milliseconds before this attempt fires. */ delay: number; } /** SDK lifecycle events emitted by {@link RosClient.on}, WebSocket link only. */ export interface RosClientEventMap { /** An established connection dropped unexpectedly. */ disconnected: undefined; /** About to retry opening the connection. */ reconnecting: ReconnectingDetail; /** A retry succeeded and subscriptions were replayed. */ reconnected: undefined; } /** * Pair of explicit endpoints when HTTP and WebSocket live behind * different URLs (e.g. one is fronted by a TLS proxy, the other isn't). * Pass either field on its own to limit the client to that transport. */ export interface ConnectEndpoints { /** Base URL for the HTTP capability transport (`POST /capability/...`). */ http?: string; /** Full URL of the WebSocket capability endpoint. */ ws?: string; } /** * Browser-native Web Runtime client. * * The verb API (`call` / `publish` / `subscribe` / `action`) is the same * regardless of transport. Transports are picked from the URL scheme * passed to {@link connect}: * * - `ws://` / `wss://` — WebSocket only. * - `http://` / `https://` — HTTP for `call`/`publish`; SSE for `action`. * `subscribe` falls through to a sibling WebSocket at the same host * with `/capability` appended. * - {@link ConnectEndpoints} — when both URLs are provided, * HTTP for `call`/`publish`; WebSocket for `subscribe`/`action`. * * **Path conventions.** When a `ws://` / `wss://` URL is passed * without a path (or with just `/`), the SDK appends the runtime's * default `/capability` path automatically — so `'ws://host:9000'` * and `'ws://host:9000/capability'` behave identically. Pass an * explicit non-default path if your server changed `--path` / * `--http-base-path` or sits behind a path-rewriting proxy. */ export class RosClient { readonly url: string; constructor(url: string | ConnectEndpoints, options?: ConnectOptions); connect(): Promise; close(): Promise; /** Subscribe to an SDK lifecycle event — see {@link RosClientEventMap}. */ on( event: K, handler: (detail: RosClientEventMap[K]) => void ): this; /** * Remove a listener added with {@link RosClient.on}. `handler` must be * the same function reference passed to `on()` - a new closure with * equivalent behavior won't match. */ off( event: K, handler: (detail: RosClientEventMap[K]) => void ): this; /** * Invoke a service capability. * * @example Typed via the ROS service type name (preferred) * const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( * '/add_two_ints', { a: '2n', b: '40n' } * ); * console.log(reply.sum); * * @example Untyped (capability with a custom type not in the * generated maps, or quick prototyping) * const reply = await ros.call('/whatever', { foo: 1 }); */ call( capability: string, request: SvcReq ): Promise>; call(capability: string, request: unknown): Promise; /** Publish a message to a topic capability. */ publish( capability: string, message: Msg ): Promise; publish(capability: string, message: unknown): Promise; /** Subscribe to messages on a topic capability. */ subscribe( capability: string, callback: (msg: Msg) => void ): Promise; subscribe( capability: string, callback: (msg: unknown) => void ): Promise; /** * Send an action goal. * * @example Typed via the ROS action type name (preferred) * const goal = await ros.action<'example_interfaces/action/Fibonacci'>( * '/fibonacci', { order: 5 }, { onFeedback: (fb) => console.log(fb) } * ); * const result = await goal.result; * * @example Untyped (capability with a custom type not in the * generated maps, or quick prototyping) * const goal = await ros.action('/whatever', { foo: 1 }); */ action( capability: string, goal: ActionGoal, options?: { onFeedback?: (feedback: ActionFeedback) => void; } | null ): Promise>>; action( capability: string, goal: unknown, options?: { onFeedback?: (feedback: unknown) => void } | null ): Promise; } /** * Open a connection to a Web Runtime capability endpoint. * Convenience wrapper around `new RosClient(...).connect()`. * * @param url Either a single URL (`ws://`, `wss://`, `http://`, * `https://`) or a {@link ConnectEndpoints} pair. */ export function connect( url: string | ConnectEndpoints, options?: ConnectOptions ): Promise; }