{"version":3,"file":"web.cjs","names":[],"sources":["../web/client.js"],"sourcesContent":["// Copyright (c) 2026 RobotWebTools Contributors. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n\n// Pure-JavaScript browser SDK for the rclnodejs Web Runtime.\n//\n// Authored as **ESM** so the browser's native module loader (and any\n// modern bundler) can consume it directly without a CJS-to-ESM\n// transform. Ships with a `type: module` web/package.json so Node\n// also treats this file as ESM.\n//\n// In a real browser, `WebSocket` and `fetch` are globals. In Node —\n// used by the integration tests and SSR scenarios — we fall back to\n// the optional `ws` package via dynamic import (Node ≥ 18 has fetch\n// natively, no extra dep needed).\n//\n// This module never imports rclnodejs itself — zero native deps,\n// safe to bundle for the browser.\n//\n// Two transports are supported, picked from the URL scheme:\n//\n//   - ws:// / wss://       → WebSocket only (call/publish/subscribe/action).\n//   - http:// / https://   → HTTP for call/publish; SSE for action.\n//                            Subscribe lazily uses a sibling WebSocket.\n//   - { http, ws }         → HTTP for call/publish; WS for subscribe/action.\n\nlet WS = globalThis.WebSocket;\nlet _wsResolved = !!WS;\n\n// Resolve a Node WebSocket implementation lazily. This avoids a top-level\n// `await import('ws')`, which is unavailable in the CommonJS build. In browsers\n// `globalThis.WebSocket` is used and the `ws` package is never touched.\nasync function _ensureWS() {\n  if (_wsResolved) {\n    return WS;\n  }\n  _wsResolved = true;\n  try {\n    const wsModule = await import('ws');\n    WS = wsModule.WebSocket || wsModule.default;\n  } catch {\n    // No WebSocket implementation available in this environment.\n  }\n  return WS;\n}\n\n// Frame ids are UUIDs so they never collide across sessions or modules\n// that share a single RosClient. Use the platform RNG when available\n// (browsers and Node ≥ 16.7) and fall back to a small RFC-4122 v4\n// implementation otherwise.\nconst _genId =\n  globalThis.crypto && typeof globalThis.crypto.randomUUID === 'function'\n    ? () => globalThis.crypto.randomUUID()\n    : () => {\n        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n          const r = (Math.random() * 16) | 0;\n          const v = c === 'x' ? r : (r & 0x3) | 0x8;\n          return v.toString(16);\n        });\n      };\n\n// Exponential backoff with jitter (half fixed, half random) used by WS reconnect.\nfunction _backoffDelay(attempt, { baseMs = 500, maxMs = 30000 } = {}) {\n  const capped = Math.min(baseMs * 2 ** attempt, maxMs);\n  return capped / 2 + Math.random() * (capped / 2);\n}\n\n// -------------------------------------------------------------------\n// Internal \"link\" — the WebSocket transport. Hidden from the public API.\n// -------------------------------------------------------------------\n\n/**\n * WebSocket link. Speaks the capability frame protocol used by\n * `WebSocketTransport` on the server. Long-lived; supports `call`,\n * `publish`, `subscribe`, `unsubscribe`, and `action`.\n *\n * With `options.reconnect`, a drop after a successful open reopens with\n * backoff and replays subscriptions under the same `subId`. The *first*\n * connection attempt is unaffected — a bad URL still rejects once.\n */\nclass _WsLink {\n  /**\n   * @param {string} url\n   * @param {object} [options]\n   * @param {boolean} [options.reconnect=false] See class doc above.\n   * @param {(event: string, detail: unknown) => void} [options.onEvent]\n   *   Notified for 'disconnected' / 'reconnecting' / 'reconnected'.\n   */\n  constructor(url, options = {}) {\n    this.url = url;\n    this._isReconnectEnabled = !!options.reconnect;\n    this._onEvent = options.onEvent || (() => {});\n    this._ws = null;\n    this._openFailed = false;\n    this._pending = new Map();\n    this._subs = new Map();\n    this._goals = new Map(); // goal id -> { onFeedback, resolveResult, rejectResult }\n    this._closed = false;\n    this._isUserClosed = false;\n    this._isReconnecting = false;\n    this._reconnectAttempt = 0;\n    this._reconnectTimer = null;\n  }\n\n  /** First-time open. Rejects once if the initial connection fails. */\n  async connect() {\n    return this._open();\n  }\n\n  /** Open (or reopen, on reconnect) the underlying WebSocket. */\n  async _open() {\n    await _ensureWS();\n    return new Promise((resolve, reject) => {\n      if (!WS) {\n        return reject(\n          new Error(\n            'no WebSocket implementation available; provide a global WebSocket or install the optional `ws` package'\n          )\n        );\n      }\n      const ws = new WS(this.url);\n      this._ws = ws;\n      this._openFailed = false;\n      let isOpened = false;\n      const onOpen = () => {\n        isOpened = true;\n        this._reconnectAttempt = 0;\n        this._isReconnecting = false;\n        this._resubscribeAll();\n        resolve();\n      };\n      const onError = (err) => {\n        // Ignore post-open: 'close' always follows and _handleClose() owns failing pending requests.\n        if (!isOpened) {\n          if (this._ws === ws) this._openFailed = true;\n          reject(err && err.error ? err.error : err);\n        }\n      };\n      const onClose = () => {\n        if (isOpened) {\n          this._handleClose();\n          return;\n        }\n        reject(new Error('connection closed before it was established'));\n      };\n      const onMessage = (ev) => this._onMessage(ev);\n\n      if (ws.addEventListener) {\n        ws.addEventListener('open', onOpen, { once: true });\n        ws.addEventListener('error', onError);\n        ws.addEventListener('close', onClose, { once: true });\n        ws.addEventListener('message', onMessage);\n      } else {\n        ws.once('open', onOpen);\n        ws.on('error', onError);\n        ws.once('close', onClose);\n        ws.on('message', (data) => onMessage({ data }));\n      }\n    });\n  }\n\n  /** Handle an unexpected close: fail in-flight requests, then finalize or reconnect. */\n  _handleClose() {\n    if (this._isUserClosed) {\n      this._failAll(new Error('connection closed'));\n      this._finalizeClosed();\n      return;\n    }\n    this._onEvent('disconnected', undefined);\n    if (!this._isReconnectEnabled) {\n      this._failAll(_connectionLostError(false));\n      this._finalizeClosed();\n      return;\n    }\n    this._failAll(_connectionLostError(true));\n    this._isReconnecting = true;\n    this._scheduleReconnect();\n  }\n\n  /** Shared terminal state for a deliberate close or a non-reconnecting drop. */\n  _finalizeClosed() {\n    this._closed = true;\n    this._isReconnecting = false;\n    this._subs.clear();\n  }\n\n  _scheduleReconnect() {\n    const attempt = this._reconnectAttempt++;\n    const delay = _backoffDelay(attempt);\n    this._onEvent('reconnecting', { attempt: attempt + 1, delay });\n    this._reconnectTimer = setTimeout(() => {\n      this._reconnectTimer = null;\n      this._open().then(\n        () => this._onEvent('reconnected', undefined),\n        // close() aborting this in-flight attempt also lands here - don't\n        // keep retrying past a deliberate close.\n        () => {\n          if (!this._isUserClosed) this._scheduleReconnect();\n        }\n      );\n    }, delay);\n  }\n\n  /**\n   * Replay every active subscription after a reopen, reusing each `subId`.\n   * Known gap: a `not_exposed` ack for a since-removed capability has no\n   * pending entry to reject, so it's silently dropped.\n   */\n  _resubscribeAll() {\n    for (const [subId, { capability }] of this._subs) {\n      this._sendRaw({ id: subId, kind: 'subscribe', capability });\n    }\n  }\n\n  call(capability, payload) {\n    return this._request({ kind: 'call', capability, payload });\n  }\n\n  publish(capability, payload) {\n    return this._request({ kind: 'publish', capability, payload });\n  }\n\n  action(capability, payload, options) {\n    if (this._closed || this._isUserClosed) {\n      return Promise.reject(new Error('connection closed'));\n    }\n    if (this._isReconnecting) {\n      return Promise.reject(_connectionLostError());\n    }\n    const { onFeedback } = options ?? {};\n    const id = _genId();\n    // Register the goal before sending to avoid dropping feedback that\n    // arrives before the acknowledgement.\n    let resolveResult, rejectResult;\n    const result = new Promise((res, rej) => {\n      resolveResult = res;\n      rejectResult = rej;\n    });\n    let status;\n    this._goals.set(id, {\n      onFeedback,\n      resolveResult,\n      rejectResult,\n      setStatus(value) {\n        status = value;\n      },\n    });\n    return new Promise((resolve, reject) => {\n      this._pending.set(id, {\n        resolve: () => {\n          resolve({\n            goalId: id,\n            result,\n            get status() {\n              return status;\n            },\n            cancel: () => this._cancelGoal(id),\n          });\n        },\n        reject: (err) => {\n          // Acceptance was not confirmed; stop local tracking.\n          this._goals.delete(id);\n          reject(err);\n        },\n      });\n      this._sendRaw({\n        id,\n        kind: 'action',\n        op: 'send_goal',\n        capability,\n        payload,\n      });\n    });\n  }\n\n  async _cancelGoal(goalId) {\n    await this._request({ kind: 'action', op: 'cancel', goalId });\n  }\n\n  subscribe(capability, callback) {\n    if (this._isReconnecting) {\n      return Promise.reject(_connectionLostError());\n    }\n    const id = _genId();\n    return new Promise((resolve, reject) => {\n      this._pending.set(id, {\n        resolve: () => {\n          this._subs.set(id, { capability, callback });\n          resolve({\n            subId: id,\n            close: () => this._unsubscribe(id),\n          });\n        },\n        reject,\n      });\n      this._sendRaw({ id, kind: 'subscribe', capability });\n    });\n  }\n\n  _unsubscribe(subId) {\n    this._subs.delete(subId);\n    return this._request({ kind: 'unsubscribe', subId });\n  }\n\n  async close() {\n    this._isUserClosed = true;\n    if (this._reconnectTimer) {\n      clearTimeout(this._reconnectTimer);\n      this._reconnectTimer = null;\n    }\n    if (!this._ws || this._closed) {\n      this._finalizeClosed();\n      return;\n    }\n    const ws = this._ws;\n    // Already closed (e.g. mid-backoff) means 'close' won't fire again, so\n    // finalize directly instead of leaving state as if still reconnecting.\n    if (ws.readyState === 3) {\n      this._finalizeClosed();\n      return;\n    }\n    return new Promise((resolve) => {\n      const onClose = () => {\n        if (ws.removeEventListener) {\n          ws.removeEventListener('close', onClose);\n        } else {\n          ws.off('close', onClose);\n        }\n        // Covers the case where this ws never reached 'open' (e.g. closed\n        // mid-reconnect-attempt) and so never ran _handleClose(); harmless\n        // if it already did.\n        this._finalizeClosed();\n        resolve();\n      };\n      if (ws.addEventListener) {\n        ws.addEventListener('close', onClose, { once: true });\n      } else {\n        ws.once('close', onClose);\n      }\n      try {\n        ws.close();\n        if (this._openFailed) onClose();\n      } catch (_) {\n        this._finalizeClosed();\n        resolve();\n      }\n    });\n  }\n\n  _request(frame) {\n    return new Promise((resolve, reject) => {\n      if (this._closed) return reject(new Error('connection closed'));\n      if (this._isReconnecting) return reject(_connectionLostError());\n      const id = _genId();\n      frame.id = id;\n      this._pending.set(id, { resolve, reject });\n      this._sendRaw(frame);\n    });\n  }\n\n  _sendRaw(frame) {\n    try {\n      this._ws.send(JSON.stringify(frame));\n    } catch (e) {\n      const pend = this._pending.get(frame.id);\n      if (pend) {\n        this._pending.delete(frame.id);\n        pend.reject(e);\n      }\n    }\n  }\n\n  _onMessage(ev) {\n    let frame;\n    try {\n      const data =\n        typeof ev.data === 'string'\n          ? ev.data\n          : ev.data && ev.data.toString\n            ? ev.data.toString('utf8')\n            : String(ev.data);\n      frame = JSON.parse(data);\n    } catch (_) {\n      return;\n    }\n    if (frame.event === 'message') {\n      const sub = this._subs.get(frame.subId);\n      if (sub) {\n        try {\n          sub.callback(frame.payload);\n        } catch (_) {\n          // user callback errors don't break the dispatch loop\n        }\n      }\n      return;\n    }\n    if (frame.event === 'feedback') {\n      const goal = this._goals.get(frame.goalId);\n      if (goal && goal.onFeedback) {\n        try {\n          goal.onFeedback(frame.payload);\n        } catch (_) {\n          // user callback errors don't break the dispatch loop\n        }\n      }\n      return;\n    }\n    if (frame.event === 'result') {\n      const goal = this._goals.get(frame.goalId);\n      this._goals.delete(frame.goalId);\n      if (goal) {\n        goal.setStatus(_normaliseActionStatus(frame.status));\n        if (frame.ok === false) {\n          goal.rejectResult(\n            Object.assign(new Error(frame.error || 'action failed'), {\n              code: frame.code,\n            })\n          );\n        } else {\n          goal.resolveResult(frame.payload);\n        }\n      }\n      return;\n    }\n    const pend = this._pending.get(frame.id);\n    if (!pend) return;\n    this._pending.delete(frame.id);\n    if (frame.ok) pend.resolve(frame.payload);\n    else\n      pend.reject(\n        Object.assign(new Error(frame.error || 'request failed'), {\n          code: frame.code,\n        })\n      );\n  }\n\n  _failAll(err) {\n    const cause = err instanceof Error ? err : new Error(String(err));\n    for (const p of this._pending.values()) {\n      p.reject(cause);\n    }\n    this._pending.clear();\n    for (const goal of this._goals.values()) {\n      goal.rejectResult(cause);\n    }\n    this._goals.clear();\n  }\n}\n\n/**\n * HTTP link for `call`/`publish` and SSE actions via `HttpTransport`.\n * Subscriptions use the WebSocket link.\n */\nclass _HttpLink {\n  constructor(baseUrl) {\n    // Normalise: strip trailing slash so we can append the path. If\n    // the user URL already ends with `/capability` (e.g. they spelled\n    // it out explicitly, mirroring the WS form), don't double-prefix\n    // it on every fetch. The default-runtime layout still works for\n    // the bare-host form `'http://host:9001'` — we just append the\n    // default path ourselves below.\n    const trimmed = baseUrl.replace(/\\/+$/, '');\n    this.baseUrl = trimmed.endsWith('/capability')\n      ? trimmed\n      : trimmed + '/capability';\n    this._actionControllers = new Set();\n  }\n\n  async connect() {\n    // Stateless — nothing to open. We don't probe the server here so\n    // that connect() stays cheap; the first call() will surface any\n    // wrong-URL or wrong-port errors instead.\n  }\n\n  async close() {\n    for (const controller of this._actionControllers) {\n      controller.abort(_connectionLostError(false));\n    }\n    this._actionControllers.clear();\n  }\n\n  call(capability, payload) {\n    return this._fetch('call', capability, payload, /* expectBody */ true);\n  }\n\n  publish(capability, payload) {\n    return this._fetch('publish', capability, payload, /* expectBody */ false);\n  }\n\n  /** POST a goal and stream feedback/results; use WebSocket for cancellation. */\n  async action(capability, payload, { onFeedback } = {}) {\n    const url = this.baseUrl + '/action/' + _encodeRosName(capability);\n    const controller = new AbortController();\n    const { signal } = controller;\n    this._actionControllers.add(controller);\n    let res;\n    try {\n      res = await fetch(url, {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify(payload ?? {}),\n        signal,\n      });\n      signal.throwIfAborted();\n    } catch (e) {\n      this._actionControllers.delete(controller);\n      if (signal.aborted) throw signal.reason;\n      throw Object.assign(new Error(`HTTP request failed: ${e.message}`), {\n        code: 'network_error',\n      });\n    }\n\n    if (!res.ok || !res.body) {\n      let err = {};\n      try {\n        err = await res.json();\n      } catch (_) {\n        // Fall back to the HTTP status for non-JSON errors.\n      } finally {\n        this._actionControllers.delete(controller);\n      }\n      signal.throwIfAborted();\n      throw Object.assign(new Error(err.error || `HTTP ${res.status}`), {\n        code: err.code || 'http_' + res.status,\n        status: res.status,\n      });\n    }\n\n    let resolveResult, rejectResult;\n    const result = new Promise((res2, rej2) => {\n      resolveResult = res2;\n      rejectResult = rej2;\n    });\n    let status;\n    _pumpActionStream(\n      res.body,\n      onFeedback,\n      resolveResult,\n      rejectResult,\n      (value) => {\n        status = value;\n      },\n      signal\n    ).finally(() => this._actionControllers.delete(controller));\n    return {\n      goalId: _genId(),\n      result,\n      get status() {\n        return status;\n      },\n      cancel: () =>\n        Promise.reject(\n          Object.assign(new Error('action cancel is not supported over HTTP'), {\n            code: 'unsupported_kind',\n          })\n        ),\n    };\n  }\n\n  async _fetch(kind, capability, payload, expectBody) {\n    const url = this.baseUrl + '/' + kind + '/' + _encodeRosName(capability);\n    let res;\n    try {\n      res = await fetch(url, {\n        method: 'POST',\n        headers: { 'content-type': 'application/json' },\n        body: JSON.stringify(payload ?? {}),\n      });\n    } catch (e) {\n      throw Object.assign(new Error(`HTTP request failed: ${e.message}`), {\n        code: 'network_error',\n      });\n    }\n\n    if (res.status === 204) return undefined;\n\n    const contentType = res.headers.get('content-type') || '';\n    let body;\n    if (contentType.includes('application/json')) {\n      try {\n        body = await res.json();\n      } catch (e) {\n        throw Object.assign(\n          new Error(`invalid JSON in HTTP response: ${e.message}`),\n          { code: 'invalid_response' }\n        );\n      }\n    } else if (res.ok) {\n      body = await res.text();\n    } else {\n      body = { ok: false, error: await res.text(), code: 'http_' + res.status };\n    }\n\n    if (!res.ok) {\n      const err = body && typeof body === 'object' ? body : {};\n      throw Object.assign(new Error(err.error || `HTTP ${res.status}`), {\n        code: err.code || 'http_' + res.status,\n        status: res.status,\n      });\n    }\n    return expectBody ? body : undefined;\n  }\n}\n\nfunction _normaliseActionStatus(status) {\n  return ['succeeded', 'canceled', 'aborted'].includes(status)\n    ? status\n    : 'unknown';\n}\n\nfunction _connectionLostError(reconnecting = true) {\n  return Object.assign(\n    new Error(\n      reconnecting ? 'connection lost; reconnecting' : 'connection lost'\n    ),\n    { code: 'connection_lost' }\n  );\n}\n\n/** Runs independently; terminal SSE events settle the result promise. */\nasync function _pumpActionStream(\n  body,\n  onFeedback,\n  resolveResult,\n  rejectResult,\n  setStatus,\n  signal\n) {\n  let reader;\n  let buffer = '';\n  let skipLeadingLF = false;\n  try {\n    reader = body.getReader();\n    const decoder = new TextDecoder();\n    for (;;) {\n      signal.throwIfAborted();\n      const { done, value } = await reader.read();\n      signal.throwIfAborted();\n      if (done) break;\n      let text = decoder.decode(value, { stream: true });\n      if (text.length === 0) continue;\n      // A CRLF split across reads is one line ending, not an empty line.\n      if (skipLeadingLF && text.startsWith('\\n')) text = text.slice(1);\n      skipLeadingLF = text.endsWith('\\r');\n      buffer += text.replace(/\\r\\n?/g, '\\n');\n      let boundary;\n      while ((boundary = buffer.indexOf('\\n\\n')) !== -1) {\n        signal.throwIfAborted();\n        const chunk = buffer.slice(0, boundary);\n        buffer = buffer.slice(boundary + 2);\n        const { event, data } = _parseSseChunk(chunk);\n        if (event === 'feedback' && onFeedback) {\n          try {\n            onFeedback(data);\n          } catch (_) {\n            // Callback errors must not interrupt result delivery.\n          }\n        } else if (event === 'result') {\n          if (data === undefined) {\n            rejectResult(\n              Object.assign(new Error('invalid JSON in action result event'), {\n                code: 'invalid_response',\n              })\n            );\n            return;\n          }\n          setStatus(_normaliseActionStatus(data?.status));\n          resolveResult(\n            data && data.payload !== undefined ? data.payload : data\n          );\n          return;\n        } else if (event === 'error') {\n          setStatus(_normaliseActionStatus(data?.status));\n          rejectResult(\n            Object.assign(new Error((data && data.error) || 'action failed'), {\n              code: data && data.code,\n            })\n          );\n          return;\n        }\n      }\n    }\n    rejectResult(\n      Object.assign(new Error('action stream ended before a terminal result'), {\n        code: 'connection_lost',\n      })\n    );\n  } catch (e) {\n    rejectResult(\n      signal.aborted\n        ? signal.reason\n        : Object.assign(new Error(`action stream read failed: ${e.message}`), {\n            code: 'network_error',\n          })\n    );\n  } finally {\n    if (reader) {\n      try {\n        await reader.cancel();\n      } catch {\n        /* stream may already be closed */\n      }\n    }\n    if (reader) {\n      try {\n        reader.releaseLock();\n      } catch {\n        /* stream may already be released */\n      }\n    }\n  }\n}\n\nfunction _parseSseChunk(chunk) {\n  let event = 'message';\n  const dataLines = [];\n  for (const line of chunk.split('\\n')) {\n    if (line.startsWith('event:')) event = line.slice(6).trim();\n    else if (line.startsWith('data:'))\n      dataLines.push(line.slice(5).replace(/^ /, ''));\n  }\n  let data;\n  try {\n    data = JSON.parse(dataLines.join('\\n'));\n  } catch (_) {\n    data = undefined;\n  }\n  return { event, data };\n}\n\n// ROS names always start with `/`. Encode each path segment so that\n// names with `~`, `:`, etc. survive routing while keeping the leading\n// slash stripped (the server adds it back).\nfunction _encodeRosName(name) {\n  return name.replace(/^\\/+/, '').split('/').map(encodeURIComponent).join('/');\n}\n\n// -------------------------------------------------------------------\n// Public surface\n// -------------------------------------------------------------------\n\n/**\n * Thin client for the rclnodejs Web Runtime capability protocol.\n *\n * Picks a transport from the URL scheme:\n *\n *   - `ws://`, `wss://`      → WebSocket only (call/publish/subscribe/action).\n *   - `http://`, `https://`  → HTTP for `call`/`publish`; SSE for `action`.\n *     `subscribe` lazily uses a sibling WebSocket at the same host\n *     with `/capability` appended.\n *   - object `{http, ws}`    → HTTP for `call`/`publish`;\n *     WebSocket for `subscribe`/`action`.\n *\n * **Path conventions.** When a `ws://` / `wss://` URL is passed\n * without a path (or with just `/`), the SDK appends the runtime's\n * default `/capability` path automatically — `'ws://host:9000'` and\n * `'ws://host:9000/capability'` therefore behave identically. Pass\n * an explicit non-default path if your server changed `--path` /\n * `--http-base-path` or sits behind a path-rewriting proxy.\n *\n * @example\n *   import { connect } from 'rclnodejs/web';\n *\n *   // WebSocket-only (path defaults to /capability)\n *   const ros = await connect('ws://robot.local:9000');\n *\n *   // HTTP for call/publish, SSE for action, WS sibling for subscribe\n *   const ros = await connect('http://robot.local:9001');\n *\n *   // Split endpoints (e.g. WS behind a different proxy)\n *   const ros = await connect({\n *     http: 'https://robot.example/api',\n *     ws:   'wss://robot.example/capability',\n *   });\n */\nexport class RosClient {\n  /**\n   * @param {string|{http?:string, ws?:string}} url\n   * @param {object} [options]\n   * @param {boolean} [options.reconnect=false] Reopen the WS link with\n   *   backoff after a drop, replaying subscriptions. Enables 'reconnecting' /\n   *   'reconnected' - see {@link RosClient#on}; 'disconnected' fires on any\n   *   unexpected drop regardless. The first connect attempt still rejects\n   *   once rather than retrying forever.\n   */\n  constructor(url, options = {}) {\n    this.options = options;\n    this._closed = false;\n    this._listeners = new Map(); // event name -> Set<handler>\n    const { httpUrl, wsUrl, wsExplicit } = _resolveUrls(url);\n    this.url = httpUrl || wsUrl;\n    // Shared by both _WsLink construction sites below (eager and lazy).\n    this._wsOptions = {\n      reconnect: !!options.reconnect,\n      onEvent: (name, detail) => this._emit(name, detail),\n    };\n    this._http = httpUrl ? new _HttpLink(httpUrl) : null;\n    this._wsUrl = wsUrl;\n    // Eagerly construct (but don't yet open) the WS link when the user\n    // explicitly asked for it. When the WS URL was derived from an\n    // HTTP base, leave construction lazy until subscribe().\n    this._ws = wsExplicit && wsUrl ? new _WsLink(wsUrl, this._wsOptions) : null;\n    this._wsEager = !!wsExplicit;\n    this._wsConnect = null; // memoised connect promise (in-flight or settled)\n  }\n\n  /**\n   * Subscribe to an SDK lifecycle event: 'disconnected' (fires on any\n   * unexpected drop, regardless of `reconnect`), 'reconnecting'\n   * ({attempt, delay}), or 'reconnected' (the latter two only with\n   * {reconnect: true}). `handler(detail)` is called with that event's\n   * detail, or `undefined` for 'disconnected'/'reconnected'.\n   */\n  on(event, handler) {\n    if (!this._listeners.has(event)) this._listeners.set(event, new Set());\n    this._listeners.get(event).add(handler);\n    return this;\n  }\n\n  /**\n   * Remove a listener added with {@link RosClient#on}. `handler` must\n   * be the same function reference passed to `on()` - a new closure\n   * with equivalent behavior won't match.\n   */\n  off(event, handler) {\n    this._listeners.get(event)?.delete(handler);\n    return this;\n  }\n\n  _emit(event, detail) {\n    const handlers = this._listeners.get(event);\n    if (!handlers) return;\n    for (const handler of handlers) {\n      try {\n        handler(detail);\n      } catch (_) {\n        // a listener throwing must not break the caller that emitted this\n      }\n    }\n  }\n\n  /** Open the link(s). */\n  async connect() {\n    if (this._closed) throw new Error('connection closed');\n    // Open HTTP eagerly (it's a no-op anyway). Defer a derived WebSocket\n    // until subscribe(), allowing call/publish/action without a WS endpoint.\n    if (this._http) await this._http.connect();\n    if (this._wsEager) await this._ensureWs();\n    return this;\n  }\n\n  /** Close the underlying link(s). */\n  async close() {\n    this._closed = true;\n    const tasks = [];\n    if (this._http) tasks.push(this._http.close());\n    if (this._wsConnect) {\n      const link = this._ws;\n      // WS is connecting or connected — wait for the open to settle,\n      // then close even if the handshake failed.\n      tasks.push(\n        this._wsConnect.then(\n          () => link.close(),\n          () => link.close()\n        )\n      );\n    } else if (this._ws) {\n      // Constructed eagerly but connect() never ran — no-op close.\n      tasks.push(this._ws.close());\n    }\n    await Promise.all(tasks);\n  }\n\n  /**\n   * Build (and cache) the WebSocket link on first use. Throws a\n   * structured error if no WS URL is available or the open fails.\n   */\n  async _ensureWs() {\n    if (this._closed) throw new Error('connection closed');\n    if (!this._wsUrl) {\n      throw Object.assign(\n        new Error(\n          'no WebSocket endpoint available; connect() was given an HTTP-only URL with no WS sibling'\n        ),\n        { code: 'transport_unavailable' }\n      );\n    }\n    if (this._wsConnect) return this._wsConnect; // open is in-flight or done.\n    // Reuse the eagerly-constructed link if present, otherwise build it\n    // now (HTTP-derived sibling case).\n    if (!this._ws) this._ws = new _WsLink(this._wsUrl, this._wsOptions);\n    const link = this._ws;\n    this._wsConnect = link.connect().then(\n      () => link,\n      (err) => {\n        this._wsConnect = null; // allow retry on the next WebSocket operation\n        throw Object.assign(\n          new Error(\n            `failed to open WebSocket sibling at ${this._wsUrl}: ${err && err.message ? err.message : String(err)}`\n          ),\n          { code: 'transport_unavailable', cause: err }\n        );\n      }\n    );\n    return this._wsConnect;\n  }\n\n  // -- verb API --\n\n  async call(capability, payload) {\n    if (this._http) return this._http.call(capability, payload);\n    const ws = await this._ensureWs();\n    return ws.call(capability, payload);\n  }\n\n  async publish(capability, payload) {\n    if (this._http) return this._http.publish(capability, payload);\n    const ws = await this._ensureWs();\n    return ws.publish(capability, payload);\n  }\n\n  async subscribe(capability, callback) {\n    if (typeof callback !== 'function') {\n      throw new TypeError('subscribe(capability, callback): callback required');\n    }\n    const ws = await this._ensureWs();\n    return ws.subscribe(capability, callback);\n  }\n\n  /**\n   * Return `{ goalId, result, status, cancel() }` for an action goal.\n   * Await `result` for the ROS payload, then inspect terminal `status`.\n   * HTTP `cancel()` rejects with `unsupported_kind`; use WebSocket to cancel.\n   * @param {string} capability\n   * @param {*} payload The goal.\n   * @param {object|null} [options]\n   * @param {(feedback: *) => void} [options.onFeedback]\n   */\n  async action(capability, payload, options) {\n    const { onFeedback } = options ?? {};\n    if (onFeedback !== undefined && typeof onFeedback !== 'function') {\n      throw new TypeError(\n        'action(capability, payload, options): onFeedback must be a function'\n      );\n    }\n    if (this._closed) throw new Error('connection closed');\n    if (this._http && !this._wsEager) {\n      return this._http.action(capability, payload, { onFeedback });\n    }\n    const ws = await this._ensureWs();\n    return ws.action(capability, payload, { onFeedback });\n  }\n}\n\n/**\n * Resolve the user-supplied `connect()` URL into an `{httpUrl, wsUrl}`\n * pair plus a `wsExplicit` flag (true when the caller named a WS URL\n * themselves, false when we derived one from an HTTP base). Either\n * URL may be `null` — the corresponding link then isn't constructed\n * and verbs needing it reject with `transport_unavailable`.\n */\nfunction _resolveUrls(url) {\n  // Form 1: explicit { http, ws } pair.\n  if (url && typeof url === 'object' && !Array.isArray(url)) {\n    const httpUrl = _validateEndpoint(url.http, 'http');\n    const wsUrl = _normaliseWsPath(_validateEndpoint(url.ws, 'ws'));\n    if (!httpUrl && !wsUrl) {\n      throw new TypeError(\n        'connect({http, ws}): at least one of http or ws must be provided'\n      );\n    }\n    return { httpUrl, wsUrl, wsExplicit: !!wsUrl };\n  }\n\n  // Form 2: single URL string. Pick the transport from the scheme.\n  if (typeof url !== 'string' || !url) {\n    throw new TypeError(\n      'connect(url): url must be a non-empty string or {http, ws}'\n    );\n  }\n  if (/^wss?:\\/\\//i.test(url)) {\n    return { httpUrl: null, wsUrl: _normaliseWsPath(url), wsExplicit: true };\n  }\n  if (/^https?:\\/\\//i.test(url)) {\n    // HTTP base URL: derive a sibling WS URL, but open it only for\n    // subscribe().\n    return { httpUrl: url, wsUrl: _deriveWsSibling(url), wsExplicit: false };\n  }\n  throw new TypeError(\n    `connect(url): unrecognised URL scheme: ${url} (expected ws://, wss://, http://, or https://)`\n  );\n}\n\n// Append the runtime's default `/capability` path when the caller\n// passed a bare host (`ws://host:9000` or `ws://host:9000/`). Leave\n// any explicit non-empty path untouched so users behind a\n// path-rewriting proxy or with a non-default `WebSocketTransport({\n// path })` keep working. Returns the input unchanged on parse error\n// (let the underlying WebSocket constructor surface the bad URL).\nfunction _normaliseWsPath(wsUrl) {\n  if (!wsUrl) return wsUrl;\n  try {\n    const u = new URL(wsUrl);\n    if (u.pathname === '' || u.pathname === '/') {\n      u.pathname = '/capability';\n      return u.toString();\n    }\n    return wsUrl;\n  } catch (_) {\n    return wsUrl;\n  }\n}\n\n// Swap http(s) → ws(s) and append the default `/capability` path.\n// Returns null if the URL can't be parsed; verbs that need WS will\n// then surface a clear `transport_unavailable` error themselves.\nfunction _deriveWsSibling(httpUrl) {\n  try {\n    const u = new URL(httpUrl);\n    u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:';\n    u.pathname = u.pathname.replace(/\\/+$/, '') + '/capability';\n    return u.toString();\n  } catch (_) {\n    return null;\n  }\n}\n\n// Per-field config for `_validateEndpoint`. Keeps the validator\n// itself a straight three-step check (presence, type, scheme).\nconst _ENDPOINT_FIELDS = {\n  http: { schemeRe: /^https?:\\/\\//i, expected: 'http:// or https://' },\n  ws: { schemeRe: /^wss?:\\/\\//i, expected: 'ws:// or wss://' },\n};\n\n/**\n * Validate one endpoint of an `{http, ws}` pair. Returns the URL\n * unchanged on success, `null` when the field is absent, or throws\n * a clear `TypeError` when present but malformed.\n */\nfunction _validateEndpoint(value, field) {\n  if (value === undefined || value === null) return null;\n  const { schemeRe, expected } = _ENDPOINT_FIELDS[field];\n  if (typeof value !== 'string' || !value) {\n    throw new TypeError(\n      `connect({${field}}): ${field} must be a non-empty string, got ${typeof value}`\n    );\n  }\n  if (!schemeRe.test(value)) {\n    throw new TypeError(\n      `connect({${field}}): ${field} must start with ${expected} (got ${value})`\n    );\n  }\n  return value;\n}\n\n/**\n * Open a connection to a Web Runtime capability endpoint.\n *\n * See {@link RosClient} for the URL-scheme → transport mapping and\n * the path conventions assumed for the default `rclnodejs-web` server\n * layout (`/capability` on both transports). For non-default\n * `basePath` / `path` configurations, pass `{http, ws}` explicitly.\n *\n * @param {string|{http?:string, ws?:string}} url\n * @param {object} [options]\n * @returns {Promise<RosClient>}\n */\nexport async function connect(url, options) {\n  const c = new RosClient(url, options);\n  await c.connect();\n  return c;\n}\n"],"mappings":";;AA8BA,IAAI,KAAK,WAAW;AACpB,IAAI,cAAc,CAAC,CAAC;AAKpB,eAAe,YAAY;CACzB,IAAI,aACF,OAAO;CAET,cAAc;CACd,IAAI;EACF,MAAM,WAAW,MAAM,OAAO;EAC9B,KAAK,SAAS,aAAa,SAAS;CACtC,QAAQ,CAER;CACA,OAAO;AACT;AAMA,MAAM,SACJ,WAAW,UAAU,OAAO,WAAW,OAAO,eAAe,mBACnD,WAAW,OAAO,WAAW,UAC7B;CACJ,OAAO,uCAAuC,QAAQ,UAAU,MAAM;EACpE,MAAM,IAAK,KAAK,OAAO,IAAI,KAAM;EAEjC,QADU,MAAM,MAAM,IAAK,IAAI,IAAO,EAAA,CAC7B,SAAS,EAAE;CACtB,CAAC;AACH;AAGN,SAAS,cAAc,SAAS,EAAE,SAAS,KAAK,QAAQ,QAAU,CAAC,GAAG;CACpE,MAAM,SAAS,KAAK,IAAI,SAAS,KAAK,SAAS,KAAK;CACpD,OAAO,SAAS,IAAI,KAAK,OAAO,KAAK,SAAS;AAChD;;;;;;;;;;AAeA,IAAM,UAAN,MAAc;;;;;;;;CAQZ,YAAY,KAAK,UAAU,CAAC,GAAG;EAC7B,KAAK,MAAM;EACX,KAAK,sBAAsB,CAAC,CAAC,QAAQ;EACrC,KAAK,WAAW,QAAQ,kBAAkB,CAAC;EAC3C,KAAK,MAAM;EACX,KAAK,cAAc;EACnB,KAAK,2BAAW,IAAI,IAAI;EACxB,KAAK,wBAAQ,IAAI,IAAI;EACrB,KAAK,yBAAS,IAAI,IAAI;EACtB,K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