diff --git a/README.md b/README.md index defb60151..214892060 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,11 @@ [![Nightly Compatibility](https://github.com/RobotWebTools/rclnodejs/actions/workflows/nightly-compatibility.yml/badge.svg?branch=develop&event=schedule)](https://github.com/RobotWebTools/rclnodejs/actions/workflows/nightly-compatibility.yml?query=branch%3Adevelop+event%3Aschedule) -*Early-warning checks for ROS Rolling [nightlies](https://github.com/ros2/ros2/releases/tag/release-rolling-nightlies) using Node.js 27 [alpha](https://nodejs.org/en/about/previous-releases). See the [build documentation](./docs/BUILDING.md#nightly-compatibility-checks).* +*Nightly Compatibility checks: ROS Rolling [nightlies](https://github.com/ros2/ros2/releases/tag/release-rolling-nightlies) with Node.js 27 [alpha](https://nodejs.org/en/about/previous-releases). See the [build documentation](./docs/BUILDING.md#nightly-compatibility-checks).* -**rclnodejs** is a Node.js client library for [ROS 2](https://www.ros.org/) that provides comprehensive JavaScript and TypeScript APIs for developing ROS 2 solutions. +**rclnodejs** is a Node.js client library for [ROS 2](https://www.ros.org/) with JavaScript and TypeScript APIs. It supports topics, services, actions, parameters, lifecycle nodes, RxJS subscriptions, and Electron and browser apps. -**Key features:** Topics, Services, Actions, Parameters, Lifecycle Nodes, TypeScript support, RxJS Observables, Electron integration, ROS 2 in the browser (typed Web SDK + thin WebSocket gateway — `rclnodejs/web`, `rosocket`), and prebuilt binaries for Linux x64/arm64. - -New to ROS 2 or rclnodejs? Start with [Writing Your First rclnodejs Nodes](./tutorials/writing-your-first-rclnodejs-nodes.md) for project setup, publisher/subscriber examples, and service calls. +Start with [Writing Your First rclnodejs Nodes](./tutorials/writing-your-first-rclnodejs-nodes.md) for setup, topics, and service calls. ```javascript import rclnodejs from 'rclnodejs'; @@ -33,10 +31,8 @@ node.spin(); ## Documentation -- Reference: - [API Documentation](https://robotwebtools.github.io/rclnodejs/docs/index.html), [Web SDK guide](./web/README.md), [Tutorials](./tutorials/) -- Project docs: - [Efficient Usage Tips](./docs/EFFICIENCY.md), [FAQ and Known Issues](./docs/FAQ.md), [Building from Scratch](./docs/BUILDING.md), [Contributing](./docs/CONTRIBUTING.md) +- Reference: [API Documentation](https://robotwebtools.github.io/rclnodejs/docs/index.html), [Web SDK guide](./web/README.md), [Tutorials](./tutorials/) +- Project docs: [Efficient Usage Tips](./docs/EFFICIENCY.md), [FAQ and Known Issues](./docs/FAQ.md), [Building from Scratch](./docs/BUILDING.md), [Contributing](./docs/CONTRIBUTING.md) ## Installation @@ -57,13 +53,9 @@ source /opt/ros//setup.bash npm i rclnodejs ``` -For a branch or commit not yet published to npm, use -`npm install RobotWebTools/rclnodejs#`, which builds from source. +Install an unpublished branch or commit with `npm install RobotWebTools/rclnodejs#`. GitHub installs and source checkouts need newer Node.js/npm versions than the runtime minimum; see the [build guide](./docs/BUILDING.md). -Prebuilt binaries ship for Ubuntu 22.04 (Humble), 24.04 (Jazzy, Kilted) and -26.04 (Lyrical) on x64 and arm64, so most installs skip compilation; anything -else builds from source. Set `RCLNODEJS_FORCE_BUILD=1` to always build from -source, and see the [Dockerfile](./Dockerfile) for containerized development. +Prebuilt binaries cover Ubuntu 22.04 (Humble), 24.04 (Jazzy, Kilted), and 26.04 (Lyrical) on x64 and arm64. Other platforms build from source. Set `RCLNODEJS_FORCE_BUILD=1` to force compilation, or use the [Dockerfile](./Dockerfile) for container development. ### Run the examples from a clone @@ -76,66 +68,66 @@ More in [example/](https://github.com/RobotWebTools/rclnodejs/tree/develop/examp ## Bring ROS 2 to the Web -`rclnodejs` ships **two** ways to reach ROS 2 from the browser — pick one based on -how much glue you want to write. - -- **[`rclnodejs/web`](./web/README.md)** — a typed layer over your ROS 2 graph: - you allow-list capabilities in `web.json` or via CLI flags; anything else is - rejected before it reaches ROS 2. Best for typed web apps and HTTP clients. - - **Typed SDK** — `call`, `publish`, `subscribe`, and `action`, typed - from generated ROS interfaces. - - **Two transports** — WebSocket for all verbs, or HTTP (`--http-port`) - for calls, publishes, and SSE actions. Action cancellation requires - WebSocket and server acceptance. SDK subscriptions use WebSocket; - `--http-sse` enables raw HTTP subscriptions. - - **OpenAPI 3.1** — export service, topic, and action schemas with - `rclnodejs-web openapi`. - - ```ts - import type {} from 'rclnodejs'; - import { connect } from 'rclnodejs/web'; - const ros = await connect('ws://host:9000/capability'); - const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( - '/add_two_ints', { a: '2n', b: '40n' } - ); // reply.sum is typed as `${number}n` - ``` - - See the [Fibonacci action demo](./demo/web/api-playground/javascript/README.md#fibonacci-actions) - for a runnable example, or the [browser manipulator demo](./demo/web/manipulator/) - for terminal keyboard control and live Three.js visualization. - Browse all [web demos](./demo/web/README.md) by scenario and implementation. - -- **[`rosocket`](./rosocket/README.md)** — thin WebSocket gateway, - zero browser dependencies (just built-in `WebSocket` + `JSON`). - Best for quick prototypes and `roslibjs`-style apps. - - ```bash - npx rosocket --port 9000 --topic /chatter:std_msgs/msg/String - ``` +Build robot dashboards, control panels, and 3D visualizations in JavaScript or TypeScript. Your browser app connects to a Node.js runtime that handles ROS 2 communication. + +### Typed Web SDK + +[rclnodejs/web](./web/README.md) provides `call`, `publish`, `subscribe`, and `action`, with payload types derived from your generated ROS interfaces. + +- Choose which services, topics, and actions to expose in `web.json` or CLI flags. Unlisted operations are rejected before reaching ROS 2. +- Use WebSocket for all four operations, or HTTP/SSE for service calls, publishing, and actions. HTTP endpoints also work with `curl` and Postman. +- Export OpenAPI 3.1 with `rclnodejs-web openapi` for API explorers and client generation. + +With the [runtime](./web/README.md#server) and a ROS `/add_two_ints` service running: + +```ts +import type {} from 'rclnodejs'; +import { connect } from 'rclnodejs/web'; + +const ros = await connect('ws://localhost:9000/capability'); +const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( + '/add_two_ints', + { a: '2n', b: '40n' } +); +console.log(reply.sum); +await ros.close(); +``` + +SDK subscriptions and action cancellation use WebSocket; cancellation also requires server acceptance. Raw HTTP topic subscriptions are available with `--http-sse`. + +Try [Fibonacci actions in the browser](./demo/web/api-playground/javascript/README.md#fibonacci-actions), or watch a [terminal-controlled manipulator in 3D](./demo/web/manipulator/). See all [web demos](./demo/web/README.md) for setup and runnable code. + +### WebSocket URLs Without an SDK + +[rosocket](https://github.com/RobotWebTools/rclnodejs/blob/develop/rosocket/README.md) exposes one topic or service per WebSocket connection. Browser clients use only the built-in `WebSocket` and `JSON` APIs. + +```bash +npx rosocket --host 127.0.0.1 --port 9000 --topic /chatter:std_msgs/msg/String +``` ## Observable Subscriptions -rclnodejs supports [RxJS](https://rxjs.dev/) Observable subscriptions for reactive programming with ROS 2 messages — operators like `throttleTime()`, `debounceTime()`, `map()`, and `combineLatest()` build declarative message processing pipelines. See the [Observable Subscriptions Tutorial](./tutorials/observable-subscriptions.md) for the full API and runnable examples. +rclnodejs exposes topic subscriptions as [RxJS](https://rxjs.dev/) Observables. See the [Observable Subscriptions Tutorial](./tutorials/observable-subscriptions.md) for a runnable example and subscription cleanup. ## Electron-based Visualization -Build desktop ROS 2 apps with Electron + Three.js, packaged for Windows/macOS/Linux via **Electron Forge**. Featured demo: 🦾 **[manipulator](./demo/electron/manipulator)** — a two-joint arm with manual/automatic control. More in [demo/electron](./demo/electron/). +See the [Electron demos](./demo/electron/) for desktop ROS 2 apps and packaging with Electron Forge. The [manipulator](./demo/electron/manipulator/) uses Electron and Three.js to control a two-joint arm. ## ROS 2 Interface Message Generation -rclnodejs auto-generates JavaScript bindings and TypeScript declarations for every ROS 2 `.msg`, `.srv`, and `.action` interface in your sourced environment. This runs during `npm install`, so in most projects you never invoke it by hand. +rclnodejs generates JavaScript bindings and TypeScript declarations during `npm install` for ROS 2 `.msg`, `.srv`, and `.action` interfaces in your sourced environment. -If you install additional ROS packages afterwards, re-run it from your project so the new interfaces are picked up: +After adding ROS interface packages, source their workspace and run from your project: ```bash npx generate-ros-messages ``` -Generated files are written to `/node_modules/rclnodejs/generated/`. For custom `.idl` files, this repo also exposes `npm run generate-messages-idl`. +JavaScript bindings are written to `/node_modules/rclnodejs/generated/` and TypeScript declarations to `node_modules/rclnodejs/types/interfaces.d.ts`. For custom `.idl` files, this repo also exposes `npm run generate-messages-idl`. ## Using rclnodejs with TypeScript -TypeScript declaration files are included in the package and exposed through the `types` entry in `package.json`. In most projects, configuring your `tsconfig.json` is sufficient: +The package includes TypeScript declarations. Use NodeNext module resolution in `tsconfig.json`: ```jsonc { @@ -147,12 +139,12 @@ TypeScript declaration files are included in the package and exposed through the } ``` -Then `import * as rclnodejs from 'rclnodejs'` works as in the example above. See [TypeScript demos](https://github.com/RobotWebTools/rclnodejs/tree/develop/demo/typescript). +See the [TypeScript demos](./demo/typescript/). ## More -- **Performance** — faster than `rclpy` and competitive with `rclcpp` for both topic and service round-trips. Full benchmarks in [benchmark/README.md](./benchmark/README.md). -- **Companion CLI** — [`rclnodejs-cli`](https://github.com/RobotWebTools/rclnodejs-cli/) scaffolds rclnodejs application skeletons and orchestrates launch files for multi-node setups. +- [Benchmarks](./benchmark/README.md) record topic publishing and service request-response measurements for rclnodejs v1.5.0, rclcpp, and rclpy. +- [rclnodejs-cli](https://github.com/RobotWebTools/rclnodejs-cli/) creates application skeletons and launch files for multi-node setups. ## Contributing @@ -162,4 +154,4 @@ Thanks to all [contributors](CONTRIBUTORS.md)! ## License -This project abides by the [Apache License 2.0](https://github.com/RobotWebTools/rclnodejs/blob/develop/LICENSE). +Licensed under [Apache 2.0](https://github.com/RobotWebTools/rclnodejs/blob/develop/LICENSE). diff --git a/benchmark/README.md b/benchmark/README.md index 1e418399b..8fe29747d 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -1,137 +1,84 @@ # ROS 2 Client Library Benchmarks -Performance benchmarks for comparing ROS 2 client libraries: C++ (rclcpp), Python (rclpy), and JavaScript (rclnodejs). +Topic and service benchmarks for rclcpp (C++), rclpy (Python), and rclnodejs (JavaScript). ## Prerequisites -1. **ROS 2**: Install from [ros.org](https://docs.ros.org/en/lyrical/Installation.html) -2. **Node.js**: v20.20.2+ for rclnodejs (from [nodejs.org](https://nodejs.org/)) -3. **rclnodejs**: Follow [installation guide](https://github.com/RobotWebTools/rclnodejs#installation) -4. **Build Dependencies**: For C++ benchmarks: `sudo apt install libssl-dev cmake build-essential` +- Install ROS 2 with rclcpp, rclpy, `std_msgs`, and `nav_msgs`. +- For JavaScript, prepare the checkout using the [build guide](../docs/BUILDING.md). +- For C++, install `cmake`, `build-essential`, and `libssl-dev`. -## Benchmark Structure +Run from the repository root. Source ROS 2 in each terminal: -Each client library has identical benchmark tests: +```bash +source /opt/ros//setup.bash +``` -| Test Type | Description | -| ----------- | ------------------------------------------- | -| **topic** | Publisher/subscriber performance | -| **service** | Client/service request-response performance | +Build the C++ benchmarks: -## Performance Results +```bash +cmake -S benchmark/rclcpp -B benchmark/rclcpp/build +cmake --build benchmark/rclcpp/build +``` + +## Recorded Results + +Recorded on August 30, 2025, using rclnodejs v1.5.0. These are historical results, not measurements of the current release. ### Test Environment -**Hardware:** +Hardware: -- **CPU:** 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz (4 cores, 8 threads) -- **Memory:** 8GB RAM -- **Architecture:** x86_64 +- CPU: 11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz (4 cores, 8 threads) +- Memory: 8GB RAM +- Architecture: x86_64 -**Software:** +Software: -- **OS:** Ubuntu 24.04.3 LTS (WSL2) -- **Kernel:** 6.6.87.2-microsoft-standard-WSL2 -- **ROS 2:** [Jazzy Patch Release 6](https://github.com/ros2/ros2/releases/tag/release-jazzy-20250820) -- **C++ Compiler:** GCC 13.3.0 (Ubuntu 13.3.0-6ubuntu2~24.04) -- **Python:** 3.12.3 -- **Node.js:** v22.18.0 -- **rclnodejs:** [v1.5.0](https://www.npmjs.com/package/rclnodejs/v/1.5.0) +- OS: Ubuntu 24.04.3 LTS (WSL2) +- Kernel: 6.6.87.2-microsoft-standard-WSL2 +- ROS 2: [Jazzy Patch Release 6](https://github.com/ros2/ros2/releases/tag/release-jazzy-20250820) +- C++ compiler: GCC 13.3.0 (Ubuntu 13.3.0-6ubuntu2~24.04) +- Python: 3.12.3 +- Node.js: v22.18.0 +- rclnodejs: [v1.5.0](https://www.npmjs.com/package/rclnodejs/v/1.5.0) ### Benchmark Results -Benchmark parameters: 1000 iterations, 1024KB message size +1000 iterations with 1024KB topic payloads and service responses. Ratios are relative to the C++ result. | Client Library | Topic (ms) | Service (ms) | Performance Ratio | | ----------------------- | ---------- | ------------ | ------------------- | -| **rclcpp (C++)** | 168 | 627 | Baseline (fastest) | -| **rclpy (Python)** | 1,618 | 15,380 | 9.6x / 24.5x slower | -| **rclnodejs (Node.js)** | 744 | 927 | 4.4x / 1.5x slower | - -_Last updated: August 30, 2025_ - -**Notes:** - -- Topic benchmarks: All libraries completed successfully with 1024KB messages -- Service benchmarks: All libraries completed successfully with 1024KB responses -- Performance ratios are relative to C++ baseline -- C++ shows excellent performance as expected for a compiled language -- Node.js performs significantly better than Python, likely due to V8 optimizations -- Python service performance shows significant overhead with large payloads compared to topics +| rclcpp (C++) | 168 | 627 | Baseline | +| rclpy (Python) | 1,618 | 15,380 | 9.6x / 24.5x slower | +| rclnodejs (Node.js) | 744 | 927 | 4.4x / 1.5x slower | ## Running Benchmarks -### C++ (rclcpp) +Choose one implementation at a time. Start its subscriber or service in terminal 1, then run its publisher or client in terminal 2. -```bash -cd benchmark/rclcpp/ -mkdir -p build && cd build -source ~/Download/ros2-linux/local_setup.bash # Adjust path -cmake .. && make -# Run from build directory: -./publisher-stress-test -r 1000 -s 1024 -./client-stress-test -r 1000 -``` +### Topics -### Python (rclpy) +Publishes `std_msgs/msg/UInt8MultiArray`; `-s` sets the array size in KB. -```bash -cd benchmark/rclpy/ -source ~/Download/ros2-linux/local_setup.bash # Adjust path -python3 topic/publisher-stress-test.py -r 1000 -s 1024 -python3 service/client-stress-test.py -r 1000 -``` +| Library | Terminal 1: subscriber | Terminal 2: publisher | +| --- | --- | --- | +| rclcpp | `benchmark/rclcpp/build/subscription-stress-test` | `benchmark/rclcpp/build/publisher-stress-test -r 1000 -s 1024` | +| rclpy | `python3 benchmark/rclpy/topic/subscription-stress-test.py` | `python3 benchmark/rclpy/topic/publisher-stress-test.py -r 1000 -s 1024` | +| rclnodejs | `node benchmark/rclnodejs/topic/subscription-stress-test.js` | `node benchmark/rclnodejs/topic/publisher-stress-test.js -r 1000 -s 1024` | -### JavaScript (rclnodejs) +### Services -```bash -cd /path/to/rclnodejs/ # Project root -source ~/Download/ros2-linux/local_setup.bash # Adjust path -node benchmark/rclnodejs/topic/publisher-stress-test.js -r 1000 -s 1024 -node benchmark/rclnodejs/service/client-stress-test.js -r 1000 -``` - -## Test Workflow - -For complete tests, run subscriber/service first, then publisher/client: - -**Topic Test:** - -```bash -# Terminal 1: Start subscriber (adjust for your language) -python3 topic/subscription-stress-test.py # Python -./subscription-stress-test # C++ (from build dir) -node benchmark/rclnodejs/topic/subscription-stress-test.js # Node.js - -# Terminal 2: Run publisher benchmark -python3 topic/publisher-stress-test.py -r 1000 -s 1024 # Python -./publisher-stress-test -r 1000 -s 1024 # C++ (from build dir) -node benchmark/rclnodejs/topic/publisher-stress-test.js -r 1000 -s 1024 # Node.js -``` - -**Service Test:** - -```bash -# Terminal 1: Start service (adjust for your language) -python3 service/service-stress-test.py -s 1024 # Python -./service-stress-test -s 1024 # C++ (from build dir) -node benchmark/rclnodejs/service/service-stress-test.js -s 1024 # Node.js - -# Terminal 2: Run client benchmark -python3 service/client-stress-test.py -r 1000 # Python -./client-stress-test -r 1000 # C++ (from build dir) -node benchmark/rclnodejs/service/client-stress-test.js -r 1000 # Node.js -``` +Calls `nav_msgs/srv/GetMap`; `-s` sets the service's map data size in KB. -## Message Types +| Library | Terminal 1: service | Terminal 2: client | +| --- | --- | --- | +| rclcpp | `benchmark/rclcpp/build/service-stress-test -s 1024` | `benchmark/rclcpp/build/client-stress-test -r 1000` | +| rclpy | `python3 benchmark/rclpy/service/service-stress-test.py -s 1024` | `python3 benchmark/rclpy/service/client-stress-test.py -r 1000` | +| rclnodejs | `node benchmark/rclnodejs/service/service-stress-test.js -s 1024` | `node benchmark/rclnodejs/service/client-stress-test.js -r 1000` | -- **Topics**: `std_msgs/msg/UInt8MultiArray` (configurable size) -- **Services**: `nav_msgs/srv/GetMap` (map data request/response) +### What the Timers Measure -## Notes +Timing differs between runners. The JavaScript topic timer covers node, publisher, and message setup, then publishing, not subscriber delivery or round-trip latency. The service timer also includes node/client setup and service discovery. -- All benchmarks use high-precision timing for accurate measurements -- C++ provides baseline performance; Python/JavaScript show expected interpreted language overhead -- All implementations are now working correctly across the three client libraries -- Results vary by system configuration; use relative comparisons between client libraries -- Service benchmarks involve request-response cycles with substantial data payloads (OccupancyGrid maps) +These are total run times, not per-message latencies. Middleware, payload size, and hardware affect the results. diff --git a/rosocket/README.md b/rosocket/README.md index 3d86d63e1..8092a1cc0 100644 --- a/rosocket/README.md +++ b/rosocket/README.md @@ -1,163 +1,114 @@ -# rosocket — ROS 2 in the browser, no library required - -> A tiny WebSocket gateway to ROS 2 — built into `rclnodejs`. - -> **Availability:** experimental; currently only on the `develop` branch of -> `rclnodejs` and not yet part of any published release. Install from GitHub -> to try it (see the project's [Install from GitHub](../README.md#install-from-github) section): -> -> ```bash -> npm install RobotWebTools/rclnodejs#develop -> ``` - -**rosocket** is a **lightweight** WebSocket gateway that lets a **plain web -browser** (or any WebSocket-capable client) talk to ROS 2 through `rclnodejs`, -with **no extra JavaScript library** required on the client side. Browsers -only need the built-in `WebSocket` and `JSON` APIs. - -> 💡 **Building a new browser app? Start with [`rclnodejs/web`](../web/README.md).** -> It's the recommended SDK for ROS 2 in the browser — typed three-verb -> API (`call` / `publish` / `subscribe`), a reviewable per-app capability -> allow-list (`web.json`), and a `curl`-able HTTP transport for Postman / -> AI-agent tool-use. **`rosocket` (this page) is the lighter sibling**: -> one named topic or service per WebSocket, no SDK, no allow-list. Reach -> for `rosocket` when you genuinely want exactly that; reach for -> `rclnodejs/web` when you want a typed SDK, an allow-list, and HTTP -> fallback. See [`rclnodejs/web` vs. `rosbridge` + `roslibjs`](../web/README.md#4-rclnodejsweb-vs-rosbridge-roslibjs) -> in the SDK guide for the full picture. - -How it compares with the classic -[rosbridge_suite](https://github.com/RobotWebTools/rosbridge_suite) + -[roslibjs](https://github.com/RobotWebTools/roslibjs) stack: - -| | **rosocket (rclnodejs)** | **rosbridge_suite + roslibjs** | -| --- | --- | --- | -| Server process | same Node.js process as your `rclnodejs` app | separate Python ROS 2 node | -| Client-side library | none — built-in `WebSocket` + `JSON` | `roslibjs` (must be bundled/loaded) | -| Wire protocol | resource-style URLs (`/topic/`, `/service/`); frame = bare ROS message as JSON | custom JSON envelope (`op: "publish" / "subscribe" / "call_service"`, …) | -| Type discovery | URL `?type=` query, or server-side default map | advertised at runtime via envelope ops | -| Features | publish / subscribe, service client | pub/sub, services, **actions, tf, parameters, compression, PNG/CBOR, auth, …** | -| Deployment | one `npm` dep, runs anywhere Node runs | extra ROS package; version must match ROS distro | +# rosocket -## URL scheme +rosocket exposes ROS 2 topics and services over WebSocket URLs. It runs in your `rclnodejs` process; browser clients use the built-in `WebSocket` and `JSON` APIs. + +Install [rclnodejs](../README.md) with a sourced ROS 2 environment: + +```bash +npm install rclnodejs +``` -The bridge is **resource-style** — the URL *is* the topic or service name and -the WebSocket frame *is* the ROS message as JSON. +For actions, typed browser clients, or a server-side allow-list, use [rclnodejs/web](../web/README.md). + +## URL scheme | URL | Direction | Payload | | --- | --- | --- | -| `ws://host:port/topic/?type=/msg/` | server → client (subscribe) | one frame per received ROS message, JSON-serialized | -| `ws://host:port/topic/?type=/msg/` | client → server (publish) | one frame per ROS message to publish, JSON-encoded | -| `ws://host:port/service/?type=/srv/` | client → server (request) | one frame per request, JSON-encoded | -| `ws://host:port/service/?type=/srv/` | server → client (response) | one frame per response, JSON-serialized | - -Notes: - -- Each connection is dedicated to one topic or service. A single socket is - full-duplex, so the same `/topic/` socket can both publish and - subscribe at the same time. -- The `type=` query parameter can be omitted if the server was started with - `topicTypes` / `serviceTypes` defaults for that name. -- Service calls may be sent as a bare request (`{"a":1,"b":2}`) or wrapped - with a correlation id (`{"id":"c1","request":{"a":1,"b":2}}`); responses - echo the same shape (`{"id":"c1","response":{...}}`). -- Errors are reported as `{"error":""}` frames; fatal protocol errors - cause the socket to close with a `1008`/`1011` code. -- 64-bit integer fields may be sent as JSON numbers or BigInt-encoded - strings (`"12n"`); responses use the rclnodejs `toJSONSafe` encoding - (BigInts become `"n"` strings). +| `ws://host:port/topic/?type=/msg/` | server to client (subscribe) | one frame per received message | +| `ws://host:port/topic/?type=/msg/` | client to server (publish) | one frame per message to publish | +| `ws://host:port/service/?type=/srv/` | client to server (request) | one frame per request | +| `ws://host:port/service/?type=/srv/` | server to client (response) | one frame per response | + +- Each connection uses one topic or service. A topic socket can both publish and subscribe. +- Omit `type=` when the server has a `topicTypes` or `serviceTypes` entry for that name. +- Send service requests directly (`{"a":"1n","b":"2n"}`) or with an ID (`{"id":"c1","request":{"a":"1n","b":"2n"}}`). Wrapped replies use `{"id":"c1","response":{...}}`. +- Errors arrive as `{"error":""}` frames. Fatal protocol errors close the socket with code `1008` or `1011`. +- Encode 64-bit integer fields as strings such as `"12n"`, not JSON numbers. Responses use the same encoding for BigInts. ## Server side +Save as `server.mjs` and run with `node server.mjs`: + ```js -const rclnodejs = require('rclnodejs'); -const { startRosocket } = require('rclnodejs/rosocket'); +import rclnodejs from 'rclnodejs'; +import { startRosocket } from 'rclnodejs/rosocket'; await rclnodejs.init(); const node = new rclnodejs.Node('rosocket_node'); rclnodejs.spin(node); -await startRosocket({ +const bridge = await startRosocket({ node, + host: '127.0.0.1', port: 9000, - // optional: pre-declare types so clients can omit ?type= - topicTypes: { '/chatter': 'std_msgs/msg/String' }, - serviceTypes: { '/add_two_ints': 'example_interfaces/srv/AddTwoInts' }, + topicTypes: { '/chatter': 'std_msgs/msg/String' }, + serviceTypes: { '/add_two_ints': 'example_interfaces/srv/AddTwoInts' }, }); ``` -### Without `topicTypes` / `serviceTypes` +Stop the gateway with `await bridge.close()`, then call `rclnodejs.shutdown()`. -The `topicTypes` / `serviceTypes` maps are entirely optional. If you omit -them, the server stays generic and clients must specify the message type -themselves via the `?type=` query parameter on each connection: +### Without type maps + +Without type maps, clients must include the type in the URL: ```js -// server – open to any topic/service the node is allowed to access -await startRosocket({ node, port: 9000 }); +await startRosocket({ node, host: '127.0.0.1', port: 9000 }); ``` ```js -// browser – type comes from the URL const sub = new WebSocket( - 'ws://localhost:9000/topic/chatter?type=std_msgs/msg/String' + 'ws://127.0.0.1:9000/topic/chatter?type=std_msgs/msg/String' ); const cli = new WebSocket( - 'ws://localhost:9000/service/add_two_ints?type=example_interfaces/srv/AddTwoInts' + 'ws://127.0.0.1:9000/service/add_two_ints?type=example_interfaces/srv/AddTwoInts' ); ``` -The same applies to the CLI — drop `--topic` / `--service` to run a generic -gateway: `npx rosocket --port 9000`. +For the CLI, omit `--topic` and `--service` to require types in client URLs. ## CLI (`rosocket`) -A ready-to-run command is shipped as a `bin` entry, so users do not need to -write any server code: +From the repository root: ```bash -# from inside this repo -npm run rosocket -- --port 9000 \ +npm run rosocket -- --host 127.0.0.1 --port 9000 \ --topic /chatter:std_msgs/msg/String \ --service /add_two_ints:example_interfaces/srv/AddTwoInts +``` -# anywhere after `npm i rclnodejs` (or via npx) -npx rosocket --port 9000 \ +After installing the package: + +```bash +npx rosocket --host 127.0.0.1 --port 9000 \ --topic /chatter:std_msgs/msg/String \ --service /add_two_ints:example_interfaces/srv/AddTwoInts ``` -Options: `--port/-p`, `--host/-H`, `--node-name/-n`, repeatable -`--topic/-t :` and `--service/-s :`, `--help/-h`. -Pre-declared types let browsers omit the `?type=` query. +Options: `--port/-p`, `--host/-H`, `--node-name/-n`, repeatable `--topic/-t :` and `--service/-s :`, `--help/-h`. ## Browser side (no library) +Run the server above and a ROS `/add_two_ints` service of type `example_interfaces/srv/AddTwoInts`. + ```html ``` -## Why not rosbridge? - -Use this bridge when you want: +## Access control -- **Zero browser dependency** — no JavaScript library to bundle or load. -- **Zero extra process** — already in the same Node.js where your - `rclnodejs` app runs. -- **Greppable URLs** for reverse-proxy ACLs (`location /topic/...`). +The bridge listens on `0.0.0.0` by default; the examples bind to loopback. Type maps supply defaults, not an allow-list: clients can select other resources and types through their URLs. Use the `verifyClient` hook or an authenticated reverse proxy before exposing the gateway to a network. -Use a full-featured stack like rosbridge_suite when you need actions, tf, -parameter helpers, compression, throttling, or compatibility with existing -ROS web tooling. +For tf, parameter helpers, compression, or throttling, see [rosbridge_suite](https://github.com/RobotWebTools/rosbridge_suite) and [roslibjs](https://github.com/RobotWebTools/roslibjs). diff --git a/rostsd_gen/readme.md b/rostsd_gen/readme.md index 295105909..7d6e2a478 100644 --- a/rostsd_gen/readme.md +++ b/rostsd_gen/readme.md @@ -1,13 +1,21 @@ # rostsd-gen -A node.js script that creates and updates the TypeScript interfaces.d.ts declaration file with type declarations for the generated interfaces (messages and services). +Generates `types/interfaces.d.ts` for ROS 2 messages, services, and actions. It runs automatically with `npm install` and `npm run generate-messages`. -Run this script every time new interfaces are generated, see script/generate_messages.cjs +After adding interfaces, source their workspace and run from the repository root: -# run +```bash +npm run generate-messages +``` -You can update the interfaces.d.ts types manually by running the generate_tsd.cjs script. +Regenerate declarations only: +```bash +npm run generate-tsd-messages ``` + +For an installed package, run from your project directory: + +```bash node node_modules/rclnodejs/scripts/generate_tsd.cjs ``` diff --git a/scripts/npmjs-readme.md b/scripts/npmjs-readme.md index adc87525a..624f91ca2 100644 --- a/scripts/npmjs-readme.md +++ b/scripts/npmjs-readme.md @@ -1,12 +1,10 @@ # rclnodejs -`rclnodejs` is a Node.js client library for ROS 2 that provides JavaScript and TypeScript APIs for building ROS 2 applications. - -**Key features:** Topics, Services, Actions, Parameters, Lifecycle Nodes, TypeScript support, RxJS Observables, Electron integration, ROS 2 in the browser (typed Web SDK + thin WebSocket gateway — `rclnodejs/web`, `rosocket`), and prebuilt binaries for Linux x64/arm64. +`rclnodejs` is a Node.js client library for [ROS 2](https://www.ros.org/) with JavaScript and TypeScript APIs. It supports topics, services, actions, parameters, lifecycle nodes, RxJS subscriptions, and Electron and browser apps. Supported ROS 2 distributions include Humble, Jazzy, Kilted, Lyrical, and Rolling. -New to ROS 2 or rclnodejs? Start with [Writing Your First rclnodejs Nodes](https://github.com/RobotWebTools/rclnodejs/blob/develop/tutorials/writing-your-first-rclnodejs-nodes.md) for project setup, publisher/subscriber examples, and service calls. +Start with [Writing Your First rclnodejs Nodes](https://github.com/RobotWebTools/rclnodejs/blob/develop/tutorials/writing-your-first-rclnodejs-nodes.md) for setup, topics, and service calls. ```javascript import rclnodejs from 'rclnodejs'; @@ -45,7 +43,9 @@ To install from GitHub instead of npm, run: npm install RobotWebTools/rclnodejs# ``` -Prebuilt binaries ship for Ubuntu 22.04 (Humble), 24.04 (Jazzy, Kilted) and 26.04 (Lyrical) on x64 and arm64, so most installs skip compilation; anything else builds from source. Set `RCLNODEJS_FORCE_BUILD=1` to always build from source. +GitHub installs need newer Node.js/npm versions than the runtime minimum above; see the [build guide](https://github.com/RobotWebTools/rclnodejs/blob/develop/docs/BUILDING.md). + +Prebuilt binaries cover Ubuntu 22.04 (Humble), 24.04 (Jazzy, Kilted), and 26.04 (Lyrical) on x64 and arm64. Other platforms build from source. Set `RCLNODEJS_FORCE_BUILD=1` to force compilation. ## Documentation and Examples @@ -60,17 +60,19 @@ Prebuilt binaries ship for Ubuntu 22.04 (Humble), 24.04 (Jazzy, Kilted) and 26.0 ## Message Generation -rclnodejs auto-generates JavaScript message interfaces and TypeScript declarations during `npm install`, so in most projects you do not need to run anything by hand. If you install additional ROS packages **after** rclnodejs was installed, re-run the generator from your project so the new interfaces are picked up: +rclnodejs generates JavaScript bindings and TypeScript declarations during `npm install` for ROS 2 `.msg`, `.srv`, and `.action` interfaces in your sourced environment. + +After adding ROS interface packages, source their workspace and run from your project: ```bash npx generate-ros-messages ``` -Generated files are written to `/node_modules/rclnodejs/generated/`. +JavaScript bindings are written to `node_modules/rclnodejs/generated/` and TypeScript declarations to `node_modules/rclnodejs/types/interfaces.d.ts`. ## Using rclnodejs with TypeScript -TypeScript declaration files are included in the package. In most projects, configuring your `tsconfig.json` is sufficient: +The package includes TypeScript declarations. Use NodeNext module resolution in `tsconfig.json`: ```jsonc { @@ -82,44 +84,55 @@ TypeScript declaration files are included in the package. In most projects, conf } ``` -Then `import * as rclnodejs from 'rclnodejs'` works the same as the JavaScript example at the top of this README. +Use `import rclnodejs from 'rclnodejs'` as in the JavaScript example above. -## ROS 2 in the browser +## Bring ROS 2 to the Web -`rclnodejs` ships **two** ways to reach ROS 2 from the browser — pick one based on how much glue you want to write. +Build robot dashboards, control panels, and 3D visualizations in JavaScript or TypeScript. Your browser app connects to a Node.js runtime that handles ROS 2 communication. -- **`rclnodejs/web`** — a typed layer over your ROS 2 graph: you allow-list capabilities in `web.json` or via CLI flags; anything else is rejected before it reaches ROS 2. Best for typed web apps and HTTP clients. - - **Typed SDK** — `call`, `publish`, `subscribe`, and `action`, typed from generated ROS interfaces. - - **Two transports** — WebSocket for all verbs, or HTTP (`--http-port`) for calls, publishes, and SSE actions. Action cancellation requires WebSocket and server acceptance. SDK subscriptions use WebSocket; `--http-sse` enables raw HTTP subscriptions. - - **OpenAPI 3.1** — export service, topic, and action schemas with `rclnodejs-web openapi`. +### Typed Web SDK - ```ts - import type {} from 'rclnodejs'; - import { connect } from 'rclnodejs/web'; - const ros = await connect('ws://host:9000/capability'); - const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( - '/add_two_ints', { a: '2n', b: '40n' } - ); // reply.sum is typed as `${number}n` - ``` +[rclnodejs/web](https://github.com/RobotWebTools/rclnodejs/blob/develop/web/README.md) provides `call`, `publish`, `subscribe`, and `action`, with payload types derived from your generated ROS interfaces. - See the [Fibonacci action demo](https://github.com/RobotWebTools/rclnodejs/blob/develop/demo/web/api-playground/javascript/README.md#fibonacci-actions) for a runnable example. +- Choose which services, topics, and actions to expose in `web.json` or CLI flags. Unlisted operations are rejected before reaching ROS 2. +- Use WebSocket for all four operations, or HTTP/SSE for service calls, publishing, and actions. HTTP endpoints also work with `curl` and Postman. +- Export OpenAPI 3.1 with `rclnodejs-web openapi` for API explorers and client generation. - No SDK needed for subscribe — with the HTTP/SSE transport enabled (`--http-sse`, plus `--http-cors` for cross-origin), any browser streams a live ROS 2 topic via built-in `EventSource`: +With the [runtime](https://github.com/RobotWebTools/rclnodejs/blob/develop/web/README.md#server) and a ROS `/add_two_ints` service running: - ```js - const es = new EventSource('http://host:9001/capability/subscribe/chatter'); - es.onmessage = (e) => console.log(JSON.parse(e.data)); // live ROS 2 messages - ``` +```ts +import type {} from 'rclnodejs'; +import { connect } from 'rclnodejs/web'; - See the [Web SDK guide](https://github.com/RobotWebTools/rclnodejs/tree/develop/web). +const ros = await connect('ws://localhost:9000/capability'); +const reply = await ros.call<'example_interfaces/srv/AddTwoInts'>( + '/add_two_ints', + { a: '2n', b: '40n' } +); +console.log(reply.sum); +await ros.close(); +``` + +SDK subscriptions and action cancellation use WebSocket; cancellation also requires server acceptance. -- **`rosocket`** — thin WebSocket gateway, zero browser dependencies (just built-in `WebSocket` + `JSON`). Best for quick prototypes and `roslibjs`-style apps. +For browser subscriptions without an SDK, expose `/chatter` and enable HTTP with `--http-port 9001 --http-sse`. Set `--http-cors` to the frontend origin for cross-origin requests: - ```bash - npx rosocket --port 9000 --topic /chatter:std_msgs/msg/String - ``` +```js +const es = new EventSource( + 'http://localhost:9001/capability/subscribe/chatter' +); +es.onmessage = (event) => console.log(JSON.parse(event.data)); +``` - See the [rosocket guide](https://github.com/RobotWebTools/rclnodejs/tree/develop/rosocket). +Try [Fibonacci actions in the browser](https://github.com/RobotWebTools/rclnodejs/blob/develop/demo/web/api-playground/javascript/README.md#fibonacci-actions), or watch a [terminal-controlled manipulator in 3D](https://github.com/RobotWebTools/rclnodejs/tree/develop/demo/web/manipulator). See all [web demos](https://github.com/RobotWebTools/rclnodejs/tree/develop/demo/web) for setup and runnable code. + +### WebSocket URLs Without an SDK + +[rosocket](https://github.com/RobotWebTools/rclnodejs/blob/develop/rosocket/README.md) exposes one topic or service per WebSocket connection. Browser clients use only the built-in `WebSocket` and `JSON` APIs. + +```bash +npx rosocket --host 127.0.0.1 --port 9000 --topic /chatter:std_msgs/msg/String +``` ## License diff --git a/tools/jsdoc/README.md b/tools/jsdoc/README.md index cffb1175e..6b35bc23c 100644 --- a/tools/jsdoc/README.md +++ b/tools/jsdoc/README.md @@ -1,163 +1,62 @@ # JSDoc Workflow -This directory contains the custom JSDoc template, the landing-page generator, -and the staging script used to prepare the docs content that is published to -GitHub Pages. - -The published version set is curated in -[`published-versions.json`](./published-versions.json). That manifest is the -source of truth for which versions appear on the live docs site. Each staging -run rebuilds the whole site from scratch, preferring `docs-` for each -listed version and falling back to the `` release tag when no matching -documentation tag exists. The staged tree is determined by the manifest, selected -tag commits and current documentation tooling — there is no `gh-pages` branch -state to maintain. +Templates and scripts for building API docs and publishing them to GitHub Pages. ## Commands -### `npm run docs` +Run from the repository root: -Build local docs for the current workspace version. +| Command | Output | +| --- | --- | +| `npm run docs` | Current package version in `docs//`, plus `docs/index.html` | +| `npm run docs:publish` | Full publication tree in `build/published-docs/` | -Output: +`docs:publish` builds the versions in [`published-versions.json`](./published-versions.json) using temporary worktrees, then rebuilds the index and shared assets. It leaves tags unchanged and needs no previous site output or `gh-pages` branch. -- `docs//` -- `docs/index.html` +To test another manifest or output directory, pass `--manifest ` or `--out ` after `npm run docs:publish --`. -Use this to verify the docs for the version currently declared in -`package.json`. +## Documentation Source Tags -### `npm run docs:publish` - -Stage the full publishable docs tree under `build/published-docs/`. - -Behavior: - -- reads the published version set from `published-versions.json` -- selects `docs-` when available, otherwise `` -- checks that the selected source's package version matches the manifest entry -- rebuilds the selected sources in temporary worktrees without rewriting them -- rebuilds the staged landing page index - -This is the normal command to use for a new release. Rebuilds use the same inputs -when the manifest, selected tag commits and documentation tooling are unchanged. - -This does **not** rebuild docs for every historical `rclnodejs` tag — only the -curated subset listed in the manifest. To change which versions are published, -edit `published-versions.json`. - -The script reads the manifest next to it by default. Override the inputs only -for testing: - -- `--manifest ` — use a different version manifest -- `--out ` — stage into a different directory - -### Documentation Source Tags - -For `docs-*` pushes, the workflow checks out `refs/heads/develop` for the -generator, version manifest and template. Manual dispatch uses the selected -ref's commit (`github.sha`), so tooling changes can be validated before merging. -The generator selects documentation sources independently for every version -in that manifest: +For each version: 1. Use the exact `docs-` tag if it exists. 2. Otherwise use the exact `` release tag. -3. Fail if neither tag exists or the selected source declares a different - version in `package.json`. - -For example, `docs-2.3.0` can contain documentation corrections while `2.3.0` -remains unchanged. Older versions without documentation tags continue to use -their release tags. Logs identify the source selected for each version. -There are no release-specific source patches, and JSDoc errors remain fatal: -a broken documentation tag does not silently fall back to a release tag. - -Keep release tags immutable and ensure documentation-tag commits remain -API-compatible with the associated release. Commit documentation corrections, -then create or update the matching documentation tag. The local generator must -see that tag to validate its source; selecting a fixed branch alone is not enough. -Pushing a `docs-*` tag triggers a real deployment, so validate locally first. -For a remote dry run, use manual dispatch with `dry_run: true` on a branch -containing the new tooling, with the desired source tags already available. - -## New Release Example - -For a new release such as `1.9.0`: - -1. Update `package.json` to `1.9.0`. -2. Add `1.9.0` to the `versions` array in `published-versions.json`. -3. Run `npm run docs` to preview the new version locally (`docs/1.9.0/` and - `docs/index.html`). -4. Cut and push the `1.9.0` release tag. If using a separate corrected - documentation source, create a local `docs-1.9.0` tag at that commit. -5. Run `npm run docs:publish`. -6. Verify the staged output in: - - `build/published-docs/docs/1.9.0/` - - `build/published-docs/docs/index.html` - - `build/published-docs/.nojekyll` -7. Merge tooling and manifest updates into `develop` before pushing a `docs-*` - tag for automatic deployment. Alternatively, manually dispatch the workflow - from the validated tooling branch to publish the site. +3. Fail if neither tag exists or the selected source declares a different version in `package.json`. -## GitHub Actions Deployment +Keep release tags unchanged and documentation commits API-compatible with the release. For example, `docs-2.3.0` can correct docs without changing `2.3.0`. Logs show the selected tag. A broken documentation tag fails the build; it does not fall back to the release tag. -The `deploy-docs.yml` workflow (`.github/workflows/deploy-docs.yml`) automates -building and deploying docs to GitHub Pages. +Create or fetch source tags before `npm run docs:publish`. Checking out a corrected branch does not change the selected source. -### Triggers +## New Releases -- **Tag push** matching `docs-*` (e.g. `git tag docs-1.9.0 && git push origin docs-1.9.0`) — builds and deploys automatically using tooling and the full version manifest from `develop`. -- **Manual dispatch** from the Actions tab — includes a `dry_run` toggle - (defaults to `true`). Uses tooling from the selected commit, not automatically - from `develop`. Set `dry_run` to `false` to deploy. +1. Update `package.json` and add the version to `published-versions.json`. +2. Run `npm run docs` to preview the current version locally. +3. Create the release tag. If using corrected documentation, create a `docs-` tag at the documentation commit too. +4. Run `npm run docs:publish` and inspect `build/published-docs/docs//`, `build/published-docs/docs/index.html`, and `build/published-docs/.nojekyll`. +5. Merge tooling and manifest changes into `develop` before pushing a `docs-*` tag. Alternatively, dispatch the deployment workflow from the validated tooling branch with the source tags available remotely. -GitHub loads the workflow definition itself from the triggering ref before -checkout runs. A documentation tag must therefore contain this checkout rule -for automatic deployments to use it. For historical tags carrying an older -workflow, manually dispatch from a branch containing the updated workflow -instead of relying on the historical tag's deployment behavior. +## GitHub Actions Deployment -These workflow runs only execute in the upstream `RobotWebTools/rclnodejs` -repository. If you trigger the workflow from a fork, the build job is skipped, -so manual dispatches and `docs-*` tag pushes there will not run the docs build. +The [deployment workflow](../../.github/workflows/deploy-docs.yml) uses Node.js 24. -### What it does +| Trigger | Tooling source | Deployment | +| --- | --- | --- | +| `docs-*` tag push | `develop` | Always deploys the full manifest | +| Manual dispatch | Selected commit (`github.sha`) | `dry_run` defaults to `true`; set it to `false` to deploy | -1. Check out deployment tooling from `develop` for tag pushes, or the selected - commit for manual dispatch, with full history and all source tags. -2. Runs `npm run docs:publish` to stage the docs tree. This reads - `published-versions.json` and rebuilds every listed version from its - documentation tag or release-tag fallback. -3. Uploads the staged output as a Pages artifact. -4. Deploys to GitHub Pages (skipped when `dry_run` is `true`). +Pushing a `docs-*` tag, including a test tag, updates the live site. Validate locally first, then use manual dispatch with `dry_run: true` for a remote build without deployment. -The workflow only needs `contents: read` and never writes to any branch. -The manifest, Git tags and current documentation tooling reconstruct the full -site from a fresh build — no prior deployment output is required. +GitHub reads the workflow from the triggering ref before checkout. Old documentation tags may lack the checkout rule above; use manual dispatch from an updated branch for those tags. -### Pull Request and Push Validation +The workflow fetches full history and tags, runs `npm run docs:publish`, uploads a Pages artifact, and deploys unless `dry_run` is enabled. It never writes to a branch. Builds run only in `RobotWebTools/rclnodejs`; forks are skipped. -The [Linux x64 build/test workflow](../../.github/workflows/linux-x64-build-and-test.yml) -runs `npm run docs` in its Lyrical / Node 24 lane for pull requests and pushes. -The check builds the current checkout's API docs and landing page using the -publication template; invalid JSDoc annotations or generation errors fail the job. -It does not rebuild historical tags, upload artifacts or deploy to Pages. -The full publication dry run remains necessary to verify all tagged versions. - -### Testing +### Pull Request and Push Validation -- Run the workflow manually with `dry_run` enabled first to verify the build - succeeds without deploying. -- Only push a `docs-test` tag when it is acceptable to update the published - GitHub Pages site: `docs-*` tags perform a real production deploy. - Afterward, clean up the tag with: - `git tag -d docs-test && git push origin :refs/tags/docs-test`. +The [Linux x64 build/test workflow](../../.github/workflows/linux-x64-build-and-test.yml) runs `npm run docs` in its Lyrical / Node 26 lane for pull requests and pushes. It checks the current API docs and landing page; JSDoc errors fail the job. It does not build historical tags, upload artifacts, or deploy. Use a publication dry run to check the tagged versions. ## Manual Landing Page Rebuild -If the staged docs tree already exists and you only want to rebuild -`build/published-docs/docs/index.html`, run `tools/jsdoc/build-index.js` against -that docs root and point it at the package metadata for the latest published -version. +To rebuild only `build/published-docs/docs/index.html`, point `tools/jsdoc/build-index.js` at an existing staged tree and the package metadata for its latest published version. Example for published version `1.8.0`: @@ -174,10 +73,4 @@ node tools/jsdoc/build-index.js rm -rf build/published-docs/.tmp ``` -## Notes - -- The staged publish output keeps shared assets in `build/published-docs/docs/_static/`. -- `.nojekyll` must remain in the staged output because the published docs tree - uses an underscore-prefixed directory. -- `published-versions.json` is the source of truth for which versions are - published; the selected documentation/release tags are the content source. +Keep `build/published-docs/.nojekyll` in the output so Pages serves the shared assets under `docs/_static/`. diff --git a/web/README.md b/web/README.md index 832c9c609..b16ecb473 100644 --- a/web/README.md +++ b/web/README.md @@ -1,65 +1,34 @@ -# rclnodejs/web — Browser SDK guide +# rclnodejs/web -> Talk to ROS 2 from a web app — typed, allow-listed, `curl`-able, -> OpenAPI-documented. +A browser client for ROS 2 services, topics, and actions. The Node.js runtime, `rclnodejs/web/server`, exposes configured operations over WebSocket and HTTP. ROS declarations supply TypeScript types. Neither these types nor OpenAPI schemas validate payloads at runtime. -`rclnodejs/web` provides a compact ESM browser SDK. Together with the -`rclnodejs/web/server` Node.js runtime, it exposes a declarative -subset of your ROS 2 graph over WebSocket **and** plain HTTP. The -browser API has four verbs: `call`, `publish`, `subscribe`, and `action`, typed -end-to-end from your ROS 2 message, service, and action types. The same -`expose` config can be exported as an OpenAPI 3.1 document for codegen, -API explorers and HTTP tool-use. It describes the **exposed API**, not -the entire ROS graph; generated types and schemas do not imply runtime -schema enforcement. +Examples in [`demo/web/`](../demo/web/): -For runnable code see [`demo/web/`](../demo/web/): - -| Demo | Pick this if you… | +| Demo | Setup | | --- | --- | -| [API playground — JavaScript](../demo/web/api-playground/javascript/) | want a single static page — no build tools, no `npm install` for the page | -| [API playground — TypeScript](../demo/web/api-playground/typescript/) | want a typed Vite app as a starting point for your web frontend | -| [Manipulator studio](../demo/web/manipulator/) | want terminal keyboard control with a read-only Three.js browser visualization | - -## Functionality at a glance - -The table maps ROS 2 communication features to the roles a web client can -perform and the web transport each role supports. The action rows below -describe the **2.3.0 implementation**; use a checkout or package that includes -it (see the [typed playground setup](../demo/web/api-playground/typescript/README.md#run-it-two-shells)). +| [API playground (JavaScript)](../demo/web/api-playground/javascript/) | Static page; no frontend build | +| [API playground (TypeScript)](../demo/web/api-playground/typescript/) | Vite app with generated ROS types | +| [Manipulator](../demo/web/manipulator/) | Terminal keyboard control and a read-only Three.js view | -### ROS 2 roles and transport support +## Transport Support -All supported operations must be in the corresponding `expose` allow-list. -HTTP paths below use the default `/capability` base path. The roles describe -the **web client's participation**, not the complete native rclnodejs API. +The table covers web-client roles, not the full native API. HTTP paths use the default `/capability` base path. | ROS 2 role / operation | WebSocket endpoint | HTTP / SSE endpoint | SDK usage and limitations | | --------------------------------------------------- | ------------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | | Pub/Sub: topic publisher | Supported | HTTP `POST /capability/publish/`; 204 on success | `ros.publish(name, message)` | -| Pub/Sub: topic subscriber | Supported; topics share one connection | HTTP `GET /capability/subscribe/` with SSE; requires `--http-sse` or `http.sse: true` | `ros.subscribe()` uses **WS only**; HTTP consumers use `EventSource` or curl. | +| Pub/Sub: topic subscriber | Supported; topics share one connection | HTTP `GET /capability/subscribe/` with SSE; requires `--http-sse` or `http.sse: true` | `ros.subscribe()` uses WS only; HTTP consumers use `EventSource` or curl. | | Client/Service: service client | Supported | HTTP `POST /capability/call/`; JSON response | `ros.call(name, request)` calls native ROS service servers. | | Client/Service: browser-hosted service server | Not exposed | Not exposed | Browser request handling and response/disconnect lifecycle are not implemented. | -| Action client: send goals, receive feedback/results | Supported | HTTP `POST /capability/action/` with SSE; **no `--http-sse` required** | `ros.action(name, goal, { onFeedback })`; await `goal.result`, then check `goal.status`. | -| Action: client cancellation | Supported, subject to ROS server acceptance | **Not supported** | `goal.cancel()` requires WS; HTTP rejects with `unsupported_kind`. | +| Action client: send goals, receive feedback/results | Supported | HTTP `POST /capability/action/` with SSE; no `--http-sse` required | `ros.action(name, goal, { onFeedback })`; await `goal.result`, then check `goal.status`. | +| Action: client cancellation | Supported, subject to ROS server acceptance | Not supported | `goal.cancel()` requires WS; HTTP rejects with `unsupported_kind`. | | Action: browser-hosted action server | Not exposed | Not exposed | Browser goal execution and feedback/result/cancel lifecycle are not implemented. | -### Protocol notes and scope +Service and action servers run on the ROS side. -These protocols connect web clients to the runtime; service/action servers -remain on the native ROS side. HTTP actions use POST/fetch streaming; -disconnecting does **not** cancel the ROS goal. +## Server -See [connection options](#connect), [SDK operations](#the-verb-api), -[actions](#actions) and [curl/SSE recipes](#3-curl-recipes-no-javascript-at-all) -for transport details and examples. - -## 1. Server side: stand up the runtime - -> `-p rclnodejs` tells npx the `rclnodejs-web` binary lives inside the -> `rclnodejs` package; drop it once `rclnodejs` is already installed in -> the current project. For a source checkout, run `node bin/rclnodejs-web.js` -> from the repository root instead of the npx prefix below. +Use `npx -p rclnodejs rclnodejs-web`, or `npx rclnodejs-web` when the package is installed locally. From a prepared source checkout, use `node bin/rclnodejs-web.js` instead. ```bash source /opt/ros//setup.bash @@ -70,11 +39,9 @@ npx -p rclnodejs rclnodejs-web \ --publish /chatter=std_msgs/msg/String \ --subscribe /chatter=std_msgs/msg/String \ --action /fibonacci=example_interfaces/action/Fibonacci -# rclnodejs/web listening on ws://localhost:9000/capability (4 capabilities) -# also http://localhost:9001/capability (call/publish/action + subscribe (SSE)) ``` -Or feed the same allow-list from `web.json`: +The same configuration in `web.json`: ```json { @@ -97,40 +64,31 @@ Or feed the same allow-list from `web.json`: npx -p rclnodejs rclnodejs-web web.json ``` -> The `expose` block is the **public API** your browser depends on. -> Anything not listed is rejected with `code: 'not_exposed'` before -> any ROS 2 API runs. Keep it narrow. +`expose` is an allow-list. Unlisted operations fail with `code: 'not_exposed'` before dispatch to ROS 2. -The CLI does not launch ROS service/action servers or a background topic -publisher; run matching nodes separately, or use the self-contained demos. Set CORS to your -frontend's origin (here `http://localhost:8080`); CORS is not authorization. +Run the matching ROS service/action servers and topic publishers separately, or use the self-contained demos. Set CORS to your frontend's origin (here `http://localhost:8080`); CORS is not authorization. -## 2. Client side: talk to it from the browser +## Client ### Connect ```ts import type {} from 'rclnodejs'; -import { connect } from 'rclnodejs/web'; // or via esm.sh in a