{"_id":"@ananay-nag/universal-client","_rev":"2-6b6142737570f5c265cd24315a49020c","name":"@ananay-nag/universal-client","dist-tags":{"latest":"2.0.1"},"versions":{"1.0.0":{"name":"@ananay-nag/universal-client","version":"1.0.0","keywords":["grpc","socket.io","http","typescript","api","client","universal","microservices","grpc-js","grpc-client","socket-client","http-client","universal-client","multi-protocol","multi-server","cross-protocol","cross-server","cross-platform","cross-service","cross-communication","cross-service-communication","middleware","security"],"author":{"name":"Ananay Nag"},"license":"MIT","_id":"@ananay-nag/universal-client@1.0.0","maintainers":[{"name":"ananay-nag","email":"ananaynag1994s@gmail.com"}],"contributors":[{"url":"https://avatars.githubusercontent.com/u/36204888?s=48&v=4","name":"Ananay Nag","email":"ananaynag1994s@gmail.com"}],"homepage":"https://github.com/ananay-nag/universal-call#readme","bugs":{"url":"https://github.com/ananay-nag/universal-call/issues"},"dist":{"shasum":"888c066e6da9c58edf57d2c522f66107c09475fb","tarball":"https://registry.npmjs.org/@ananay-nag/universal-client/-/universal-client-1.0.0.tgz","fileCount":7,"integrity":"sha512-r4LiRLtkyxy6qVF+InpT8kQizuy+3eimWQ0oIR+z82HrqrxmnmgzXpYoSltOzO3nA8HwQAjcNSuNv3PdmHCnUw==","signatures":[{"sig":"MEYCIQDRhu8s95nrh9jkh6H2Ydd1z2BNYw7Qsm9fczouYUl/DAIhAIL0ysx8ol1rgzrJfWhWioeTv3JasW0O3J2frwZ6kYeX","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":30702},"main":"dist/index.js","types":"dist/index.d.ts","module":"dist/index.mjs","engines":{"node":">=14.0.0"},"exports":{"import":"./dist/index.mjs","require":"./dist/index.js"},"gitHead":"e1fde144eb227935df4365190a83e925a3095091","scripts":{"build":"tsup src/index.ts --dts --minify --format esm,cjs --out-dir dist","clean":"rm -rf dist","prepublishOnly":"npm run clean && npm run build"},"_npmUser":{"name":"ananay-nag","email":"ananaynag1994s@gmail.com"},"repository":{"url":"git+https://github.com/ananay-nag/universal-call.git","type":"git"},"_npmVersion":"10.8.2","description":"Universal multi-server-type client for gRPC, HTTP(S), and Socket.IO services with security middleware support.","directories":{},"_nodeVersion":"20.19.3","dependencies":{"axios":"^1.4.0","@grpc/grpc-js":"^1.8.0","socket.io-client":"^4.7.1","@grpc/proto-loader":"^0.7.5"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.5.0","typescript":"^5.8.3"},"_npmOperationalInternal":{"tmp":"tmp/universal-client_1.0.0_1753794951778_0.6050090614992794","host":"s3://npm-registry-packages-npm-production"}},"2.0.1":{"name":"@ananay-nag/universal-client","version":"2.0.1","description":"Universal multi-server-type client for gRPC, HTTP(S), and Socket.IO services with security middleware support.","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","exports":{"import":"./dist/index.mjs","require":"./dist/index.js"},"bin":{"uniclient":"dist/cli/main.js"},"scripts":{"build:lib":"tsup src/index.ts --dts --minify --format esm,cjs --out-dir dist --tsconfig tsconfig.lib.json","build:cli":"tsc -p tsconfig.cli.json","clean":"rm -rf dist","build":"npm run build:lib && npm run build:cli","prepublishOnly":"npm run clean && npm run build"},"dependencies":{"@grpc/grpc-js":"^1.8.0","@grpc/proto-loader":"^0.7.5","amqplib":"^0.10.8","axios":"^1.4.0","grpc-web":"^1.5.0","kafkajs":"^2.2.4","mqtt":"^5.14.0","nats":"^2.29.3","socket.io-client":"^4.7.1","ws":"^8.18.3"},"devDependencies":{"@types/amqplib":"^0.10.7","@types/estree":"^1.0.8","@types/node":"^24.2.0","tsup":"^8.5.0","typescript":"^5.8.3"},"keywords":["grpc","socket.io","http","typescript","api","client","grpc-client","socket-client","http-client","universal-client","multi-client","kafkajs-client","nats-client","amqp-client","mqtt-client","websocket","websocket-client","universal","microservices","grpc-js","grpc-client","socket-client","http-client","universal-client","multi-protocol","multi-server","cross-protocol","cross-server","cross-platform","cross-service","cross-communication","cross-service-communication","middleware","security"],"repository":{"type":"git","url":"git+https://github.com/ananay-nag/universal-client.git"},"author":{"name":"Ananay Nag"},"contributors":[{"name":"Ananay Nag","email":"ananaynag1994s@gmail.com","url":"https://avatars.githubusercontent.com/u/36204888?s=48&v=4"}],"license":"MIT","engines":{"node":">=14.0.0"},"publishConfig":{"access":"public"},"_id":"@ananay-nag/universal-client@2.0.1","gitHead":"c3adb0d6ee22141934b5a4b781b9ffa4afb50670","bugs":{"url":"https://github.com/ananay-nag/universal-client/issues"},"homepage":"https://github.com/ananay-nag/universal-client#readme","_nodeVersion":"20.19.3","_npmVersion":"10.8.2","dist":{"integrity":"sha512-/Y+JYQvggWyYnpodDPuTbPiSRd00+GqmHWl/rfgaUWt3DSU6SfyECisA72UVxAmaF3v7SSKWW8oiNqZUWsGyyA==","shasum":"5d81e942b85b69662caafbbb2ff8509e6c8f2c3c","tarball":"https://registry.npmjs.org/@ananay-nag/universal-client/-/universal-client-2.0.1.tgz","fileCount":8,"unpackedSize":77110,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIB0g82WUhfEO1Dx+9rCAifzlJjp1O/s0Oo6Xam9p/sOUAiBhqTPBDRAEJ3D/vE2igiO4RfJXUNXKw3pxbljpxMp5Sw=="}]},"_npmUser":{"name":"ananay-nag","email":"ananaynag1994s@gmail.com"},"directories":{},"maintainers":[{"name":"ananay-nag","email":"ananaynag1994s@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/universal-client_2.0.1_1754921240602_0.8099675713156125"},"_hasShrinkwrap":false}},"time":{"created":"2025-07-29T13:15:51.647Z","modified":"2025-08-11T14:07:20.987Z","1.0.0":"2025-07-29T13:15:51.988Z","2.0.1":"2025-08-11T14:07:20.785Z"},"bugs":{"url":"https://github.com/ananay-nag/universal-client/issues"},"author":{"name":"Ananay Nag"},"license":"MIT","homepage":"https://github.com/ananay-nag/universal-client#readme","keywords":["grpc","socket.io","http","typescript","api","client","grpc-client","socket-client","http-client","universal-client","multi-client","kafkajs-client","nats-client","amqp-client","mqtt-client","websocket","websocket-client","universal","microservices","grpc-js","grpc-client","socket-client","http-client","universal-client","multi-protocol","multi-server","cross-protocol","cross-server","cross-platform","cross-service","cross-communication","cross-service-communication","middleware","security"],"repository":{"type":"git","url":"git+https://github.com/ananay-nag/universal-client.git"},"description":"Universal multi-server-type client for gRPC, HTTP(S), and Socket.IO services with security middleware support.","contributors":[{"name":"Ananay Nag","email":"ananaynag1994s@gmail.com","url":"https://avatars.githubusercontent.com/u/36204888?s=48&v=4"}],"maintainers":[{"name":"ananay-nag","email":"ananaynag1994s@gmail.com"}],"readme":"# <img src=\"./universal-client-logo.png\" alt=\"universal-client-logo\" style=\"width:50px;margin-bottom:-15px;\"/> Universal-Client\n\n**A TypeScript‑first, plugin‑driven library for seamless, configuration‑driven communication with multi-protocol services — optimized for modern service architectures and high‑performance apps.**\n\n<img src=\"./universal-client.png\" alt=\"universal-client\" style=\"width:60%;min-width:400px; margin-left: 20%\"/>\n\n---\n\n## 🚀 Why universal-client? \n\nTired of writing separate glue code for HTTP, gRPC, Kafka, and Socket.IO? Want a **single, typed, persistent, and zero‑boilerplate way** to invoke **any service** from **any node** in your network (client, server, microservice, event handler, etc.)?  \n**universal-client** delivers exactly that.\n\n- **Direct and unified API:** No need to spin up a separate proxy, API gateway, or BFF.\n- **Low latency:** Uses pooled, persistent gRPC and Socket.IO connections.\n- **TypeScript-first:** Typed interfaces and generic results for backend, frontend, and service-to-service calls.\n- **Configurable & Extensible:** Map endpoints to protocols, routes, and remote methods via simple config.\n- **All-in-one:** HTTP(S), gRPC, Socket.IO—use any, all, anytime, anywhere.\n- **Production-ready:** Focus on business logic, never on protocol friction, reliability, or connection churn.\n\n---\n\n## ✨ Features\n\n- 🔌 **Multi-Server:** gRPC, HTTP(S), Socket.IO support (add more easily\\*)\n- 🏎️ **Persistent**: Pools gRPC & Socket clients for speed and resource efficiency.\n- 🧩 **Pluggable/Configurable:** All endpoint definitions are in JSON or JS config. Novice-friendly!\n- 🛡️ **Strong Typing:** Types/interfaces for all calls, working across browser and backend.\n- ⏱️ **Optimized Latency:** Built-in timeouts, connection reuse, minimal setup per call.\n- ♾️ **Universal Use:** Works from Node.js, Express, gRPC servers/clients, Socket servers, React/Next.js (web).\n- ◀️ **Bi-directional:** Every server can also be a client—microservices nirvana.\n- 🚦 **Error Handling:** Standardized, evented, and debuggable.\n- 📚 **Easy Extendability:** Add more protocols or custom transports as needed.\n- 🚀 **Unified API** for multiple protocols — one `.call()` for all.\n-    **Production ready** — in microservices, APIs, frontends, or edge runtimes.\n- ⏱  **Timeout control** per call or globally\n- 📦 **Streaming** support (gRPC streaming, Kafka consumers, Socket.IO event streams)\n\n## ✨ Supported Protocols\n\n✅ HTTP / HTTPS  \n✅ gRPC (`@grpc/grpc-js`) native  \n✅ **gRPC-Web** (`grpc-web` for browser/client-side use)  \n✅ Socket.IO (with connection wait + event handlers)  \n✅ Plain WebSocket  \n✅ Kafka (Producer & Consumer with pause/resume)  \n✅ NATS, AMQP, MQTT (community plugins)  \n✅ Easily extensible via `ServerTypeClient` interface\n\n---\n\n## 🔥 How is this different from ordinary API clients or SDKs?\n\n- **No API gateway or full BFF required:** Communicate _directly and programmatically_ with any protocol—no middleware layer, no DSL parsing.\n- **Multi-protocol out of the box:** HTTP, gRPC, Socket.IO, all are first-class.\n- **Configuration, not code:** Change protocol/server mappings instantly—no redeploy.\n- **Strong, static typing:** Share interfaces with backend and frontend—no more `any`s or manual axios calls.\n- **Persistent**: gRPC and Socket.IO connections are reused, not reopened every call.\n- **Easy to embed**: Use just like any DB driver or HTTP lib, but works with every protocol you care about.\n- **Ideal for...** microservices, modern SaaS, DDD, cloud-native, and “polyglot” architectures.\n\n---\n\n## ⚡️ Example Use Cases\n\n- **React UI making real-time and HTTP calls through a unified method**\n- **Express middleware service exchanging data with both gRPC and HTTP services**\n- **A gRPC server acting as a client to HTTP and Socket.IO backends**\n- **Chat server sending analytics events to REST microservices**\n\n---\n\n## 📦 Installation\n\n```bash\n    npm install @ananay-nag/universal-client\n    or\n    yarn add @ananay-nag/universal-client\n```\n\n---\n\n## 🛠️ Quick Start\n\n### 1. Define your endpoints and protocols\n\n```typescript\nimport { UniversalClient, UniversalClientConfig } from \"@ananay-nag/universal-client\";\n\n\nconst config: UniversalClientConfig = {\n  endpoints: {\n    // gRPC native\n    createUser: {\n      serverType: SupportedServerTypes.GRPC,\n      host: \"localhost\",\n      port: 50051,\n      protoFile: \"./protos/user.proto\",\n      packageName: \"user\",\n      serviceName: \"UserService\",\n      methodName: \"CreateUser\",\n    },\n    // gRPC-Web (browser friendly)\n    sayHelloWeb: {\n      serverType: SupportedServerTypes.GRPCWEB,\n      host: \"http://localhost:8080\",\n      serviceName: \"GreeterService\",\n      methodName: \"sayHello\",\n      createClient: (address: string) => new GreeterServiceClient(address),\n      options: {  \n        timeoutMs: 10000\n      },\n    },\n    // HTTP\n    signup: {\n      serverType: SupportedServerTypes.HTTP,\n      host: \"http://localhost:4000\",\n      path: \"/api/signup\",\n      methodName: \"POST\",\n    },\n    // Socket.IO with event handler for server pushes\n    receiveEmits: {\n      serverType: SupportedServerTypes.SOCKETIO,\n      host: \"http://localhost:3002\",\n      port: 3002,\n      eventHandler: (socket: Socket) => {\n        socket.on(\"serverEvent\", console.log);\n      },\n    },\n    sendChat: {\n      protocol: SupportedServerTypes.SOCKETIO,\n      host: \"http://localhost\",\n      port: 3001,\n      event: \"sendChat\",\n    },\n    // Kafka Producer\n    kafkaProducer: {\n      serverType: SupportedServerTypes.KAFKA,\n      host: \"localhost:9092\",\n      topic: \"chat\",\n      mode: \"producer\"\n      options: {},\n    },\n    // Kafka Consumer\n    kafkaConsumer: {\n      serverType: SupportedServerTypes.KAFKA,\n      host: \"localhost:9092\",\n      groupId: \"chat-group\",\n      topic: \"chat\",\n      mode: \"consumer\",\n      options: {\n        fromBeginning: true,\n      },\n      messageHandler: async ({ topic, partition, message }: any) => {\n        console.log(`${topic} [${partition}]: ${message.value.toString()}`);\n      },\n    },\n  },\n};\n\nconst client = new UniversalClient(config);\n```\n\n### 2. Create and use your client anywhere\n\n```typescript\n// gRPC native call\nawait client.call(\"createUser\", { username: \"alice\", email: \"test@example.com\" });\n\n// gRPC-Web call\nawait client.call(\"sayHelloWeb\", new HelloRequest().setName(\"World\"));\n\n// HTTP POST\nawait client.call(\"signup\", { username: \"bob\", password: \"secure\" });\n\n// Socket.IO emit\nawait client.call(\"sendChat\", { message: \"Hello real-time!\" });\n\n// Kafka produce\nawait client.call(\"kafkaProducer\", { userId: 1, message: \"Hi Kafka\" });\n\n// Kafka control (pause consumer)\nawait client.call(\"kafkaConsumer\", null, { methodName: \"pause\" });\n\n```\n\n---\n\n## ⚙️ Middleware (Auth Example)\n\n```typescript\nimport { AuthJwtPlugin } from \"@ananay-nag/universal-client\";\n\nfunction getToken() {\n  return localStorage.getItem(\"jwtToken\") || \"\";\n}\n\nclient.useMiddleware(AuthJwtPlugin(getToken));\n```\n\n---\n\n## 🏗️ Examples\n\n### a) In a gRPC server (service-to-service communication):\n\n```RPC\n// gRPC handler\nasync function CreateUser(call, callback) {\n// Notify chat via Socket.IO and signup via HTTP/S\nawait universalClient.call('sendChat', { message: ${call.request.username} signed up! });\nawait universalClient.call('signup', { ...call.request, password: 'auto-gen' });\n// Respond as normal\ncallback(null, { id: '42', ...call.request });\n}\n```\n\n### b) In a Socket.IO server:\n\n```typescript\nio.on(\"connection\", (socket) => {\n  socket.on(\"register\", async (payload, cb) => {\n    const user = await universalClient.call(\"createUser\", payload); // gRPC call\n    cb({ user });\n  });\n});\n```\n\n### c) In an Express API:\n\n```typescript\napp.post('/user', async (req, res) => {\n  const user = await universalClient.call('createUser', req.body); // gRPC\n  await universalClient.call('sendChat', { message: New user: ${user.username} }); // Socket\n  res.json(user);\n});\n```\n\n---\n\n## 🤖 TypeScript Typings\n\nYou can define your own interfaces for request/response types—and use codegen from `.proto` files for _full type safety_.\n\n---\n\n## ⚙️ Advanced Config\n\n- **Timeouts:**  \n  Pass optional `{ timeoutMs: 5000 }` as the third argument to `.call()` for custom timeouts.\n\n- **Extending protocols:**  \n  PRs welcome! Add NATS, MQTT, Rabbit, or custom protocols by simply dropping in a new client module.\n\n---\n\n## Works with HTTP headers, gRPC metadata, Socket.IO auth handshake.\n\n---\n\n## ⚡ Socket.IO Updates\n\n- **`createClient` now waits** for connection before returning, avoiding \"not connected\" errors.\n- **`eventHandler` in config** lets you subscribe to server-emitted events once on connect.\n\n---\n\n## 📌 gRPC-Web Notes\n\n- For browsers/environments without raw gRPC, provide `createClient` in config that returns your generated grpc-web client.\n- Official `grpc-web` npm package supported.\n\n---\n\n## 🎯 Kafka Updates\n\n- Unified `kafkaPlugin` supports producer/consumer via `options.mode`.\n- Delegates send/control logic to `kafkaProducerPlugin` / `kafkaConsumerPlugin`.\n- Consumers can auto-run `messageHandler` for incoming messages.\n\n---\n\n## 🤖 TypeScript\n\nTypes are exported for:\n- `UniversalClientConfig`\n- `EndpointConfig`\n- `SupportedServerTypes`\n- `CallContext`\n- `MiddlewarePlugin` \n\n## 💡 Tips & Best Practices\n\n- Share domain model types with backends (using a `@yourorg/protos` npm package).\n- Use a config per environment (dev, staging, prod).\n- For browser-based gRPC, use `grpc-web`\\*; for Node, `@grpc/grpc-js` is native.\n- Works in Monorepo or Polyrepo architectures.\n\n---\n\n## 🖥️ API\n\n### UniversalClient\n\n- `constructor(config: UniversalClientConfig)`\n- `call<T>(key: string, payload: any, options: UniversalClientCallOptions = {}): Promise<T>`\n\n---\n\n## 🤩 Ready to Modernize Your Service Calls?\n\n**Stop copying boilerplate and juggling SDKs. Power your microservices, apps, and cross-stack comms the _intelligent_, _clean_, and _typed_ way.**\n\n---\n\n## 📄 License\n\nMIT\n\n---\n\n## 🌟 Contributing/Feedback\n\nWe welcome PRs and issues! If there's a protocol or feature you'd like, open a discussion on GitHub.\n","readmeFilename":"README.md"}