{"version":3,"file":"rosocket.cjs","names":["debug","createDebug","WebSocketServer","toJSONSafe","reviveBigInts"],"sources":["../rosocket/index.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\nimport { WebSocketServer } from 'ws';\nimport createDebug from 'debug';\nimport { toJSONSafe, reviveBigInts } from '../lib/message_serialization.js';\n\nconst debug = createDebug('rclnodejs:rosocket');\n\nfunction safeSend(ws, payload) {\n  if (ws.readyState !== ws.OPEN) return;\n  try {\n    ws.send(typeof payload === 'string' ? payload : JSON.stringify(payload));\n  } catch (e) {\n    debug('send failed: %s', e.message);\n  }\n}\n\nfunction sendError(ws, message, extra) {\n  safeSend(ws, { error: message, ...(extra || {}) });\n}\n\n// Decode a URL path into { kind, name } where kind is 'topic' or 'service'.\n// Examples:\n//   /topic/chatter            -> { kind:'topic',   name:'/chatter' }\n//   /topic/ns/sub/chatter     -> { kind:'topic',   name:'/ns/sub/chatter' }\n//   /service/add_two_ints     -> { kind:'service', name:'/add_two_ints' }\nfunction parseResourcePath(pathname) {\n  const m = /^\\/(topic|service)\\/(.+)$/.exec(pathname);\n  if (!m) return null;\n  const name = '/' + m[2].replace(/^\\/+/, '');\n  if (name.length < 2) return null;\n  return { kind: m[1], name };\n}\n\n/**\n * Start a resource-style WebSocket gateway that exposes ROS 2 topics and\n * services as plain WebSocket URLs carrying ROS messages as JSON.\n *\n * URL scheme:\n *   ws://host:port/topic/<topic_name>?type=<pkg>/msg/<Type>\n *   ws://host:port/service/<service_name>?type=<pkg>/srv/<Type>\n *\n * The browser only needs the built-in `WebSocket` and `JSON` APIs.\n *\n * @param {Object} options\n * @param {import('../lib/node.js')} options.node - rclnodejs Node to host pubs/subs/clients on.\n * @param {number} [options.port=9000] - Port to listen on.\n * @param {string} [options.host='0.0.0.0'] - Host to bind to.\n * @param {Object<string,string>} [options.topicTypes] - Optional default type per topic name (e.g. {\"/chatter\":\"std_msgs/msg/String\"}).\n * @param {Object<string,string>} [options.serviceTypes] - Optional default type per service name.\n * @param {(req: import('http').IncomingMessage) => boolean} [options.verifyClient] - Optional auth hook called with the raw HTTP upgrade request; return `false` to reject the connection.\n * @returns {Promise<{wss: WebSocketServer, close: () => Promise<void>, port: number}>}\n */\nfunction startRosocket(options = {}) {\n  const {\n    node,\n    port = 9000,\n    host = '0.0.0.0',\n    topicTypes = {},\n    serviceTypes = {},\n    verifyClient,\n  } = options;\n\n  if (!node) throw new TypeError('startRosocket: options.node is required');\n\n  // ws's verifyClient is invoked with `info = { origin, secure, req }`,\n  // not the raw IncomingMessage. Wrap it so users can write a simple\n  // `(req) => boolean` hook as documented above.\n  const wsVerifyClient = verifyClient\n    ? (info) => verifyClient(info.req)\n    : undefined;\n\n  return new Promise((resolve, reject) => {\n    const wss = new WebSocketServer({\n      host,\n      port,\n      verifyClient: wsVerifyClient,\n    });\n\n    wss.on('error', reject);\n\n    wss.on('connection', (ws, req) => {\n      const url = new URL(req.url, 'http://localhost');\n      const resource = parseResourcePath(url.pathname);\n      if (!resource) {\n        sendError(ws, `Unknown path: ${url.pathname}`);\n        ws.close(1008, 'unknown path');\n        return;\n      }\n      const typeFromQuery = url.searchParams.get('type');\n      const typeFromMap =\n        resource.kind === 'topic'\n          ? topicTypes[resource.name]\n          : serviceTypes[resource.name];\n      const typeName = typeFromQuery || typeFromMap;\n      if (!typeName) {\n        sendError(\n          ws,\n          `Missing message type. Specify ?type=<pkg>/${resource.kind === 'topic' ? 'msg' : 'srv'}/<Type> or configure it server-side.`\n        );\n        ws.close(1008, 'missing type');\n        return;\n      }\n\n      try {\n        if (resource.kind === 'topic') {\n          handleTopic(ws, node, resource.name, typeName);\n        } else {\n          handleService(ws, node, resource.name, typeName);\n        }\n      } catch (e) {\n        debug('connection setup failed: %s', e.stack || e.message);\n        sendError(ws, e.message);\n        ws.close(1011, 'setup error');\n      }\n    });\n\n    wss.on('listening', () => {\n      const addr = wss.address();\n      debug('rosocket listening on %s:%d', addr.address, addr.port);\n      resolve({\n        wss,\n        port: addr.port,\n        close: () =>\n          new Promise((res) => {\n            for (const client of wss.clients) {\n              try {\n                client.close();\n              } catch (_) {}\n            }\n            wss.close(() => res());\n          }),\n      });\n    });\n  });\n}\n\nfunction handleTopic(ws, node, topicName, typeName) {\n  // Lazily create both a publisher and a subscription on first need.\n  // The publisher is only created if/when the client publishes; the\n  // subscription is created immediately so the client receives messages.\n  let publisher = null;\n  const subscription = node.createSubscription(typeName, topicName, (msg) => {\n    safeSend(ws, toJSONSafe(msg));\n  });\n  debug('subscribed %s [%s]', topicName, typeName);\n\n  ws.on('message', (data, isBinary) => {\n    if (isBinary) {\n      sendError(ws, 'binary frames not supported on /topic/*');\n      return;\n    }\n    let msg;\n    try {\n      msg = reviveBigInts(JSON.parse(data.toString('utf8')));\n    } catch (e) {\n      sendError(ws, `invalid JSON: ${e.message}`);\n      return;\n    }\n    try {\n      if (!publisher) {\n        publisher = node.createPublisher(typeName, topicName);\n      }\n      publisher.publish(msg);\n    } catch (e) {\n      sendError(ws, `publish failed: ${e.message}`);\n    }\n  });\n\n  ws.on('close', () => {\n    try {\n      node.destroySubscription(subscription);\n    } catch (_) {}\n    if (publisher) {\n      try {\n        node.destroyPublisher(publisher);\n      } catch (_) {}\n    }\n  });\n}\n\nfunction handleService(ws, node, serviceName, typeName) {\n  const client = node.createClient(typeName, serviceName);\n  debug('service client created %s [%s]', serviceName, typeName);\n\n  ws.on('message', (data, isBinary) => {\n    if (isBinary) {\n      sendError(ws, 'binary frames not supported on /service/*');\n      return;\n    }\n    let parsed;\n    try {\n      parsed = JSON.parse(data.toString('utf8'));\n    } catch (e) {\n      sendError(ws, `invalid JSON: ${e.message}`);\n      return;\n    }\n    // Allow either bare request {a:1,b:2} or wrapped {id, request}.\n    const id = parsed && typeof parsed === 'object' ? parsed.id : undefined;\n    const request = reviveBigInts(\n      parsed && parsed.request !== undefined ? parsed.request : parsed\n    );\n\n    try {\n      client.sendRequest(request, (response) => {\n        const body = toJSONSafe(response);\n        safeSend(ws, id !== undefined ? { id, response: body } : body);\n      });\n    } catch (e) {\n      sendError(ws, `service call failed: ${e.message}`, { id });\n    }\n  });\n\n  ws.on('close', () => {\n    try {\n      node.destroyClient(client);\n    } catch (_) {}\n  });\n}\n\nexport { startRosocket };\n"],"mappings":";;;;;;AAYA,MAAMA,WAAAA,GAAQC,MAAAA,QAAAA,CAAY,oBAAoB;AAE9C,SAAS,SAAS,IAAI,SAAS;CAC7B,IAAI,GAAG,eAAe,GAAG,MAAM;CAC/B,IAAI;EACF,GAAG,KAAK,OAAO,YAAY,WAAW,UAAU,KAAK,UAAU,OAAO,CAAC;CACzE,SAAS,GAAG;EACVD,QAAM,mBAAmB,EAAE,OAAO;CACpC;AACF;AAEA,SAAS,UAAU,IAAI,SAAS,OAAO;CACrC,SAAS,IAAI;EAAE,OAAO;EAAS,GAAI,SAAS,CAAC;CAAG,CAAC;AACnD;AAOA,SAAS,kBAAkB,UAAU;CACnC,MAAM,IAAI,4BAA4B,KAAK,QAAQ;CACnD,IAAI,CAAC,GAAG,OAAO;CACf,MAAM,OAAO,MAAM,EAAE,EAAE,CAAC,QAAQ,QAAQ,EAAE;CAC1C,IAAI,KAAK,SAAS,GAAG,OAAO;CAC5B,OAAO;EAAE,MAAM,EAAE;EAAI;CAAK;AAC5B;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,cAAc,UAAU,CAAC,GAAG;CACnC,MAAM,EACJ,MACA,OAAO,KACP,OAAO,WACP,aAAa,CAAC,GACd,eAAe,CAAC,GAChB,iBACE;CAEJ,IAAI,CAAC,MAAM,MAAM,IAAI,UAAU,yCAAyC;CAKxE,MAAM,iBAAiB,gBAClB,SAAS,aAAa,KAAK,GAAG,IAC/B,KAAA;CAEJ,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,MAAM,IAAIE,GAAAA,g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