From fb555b33be95c00f9e73f9d9cd08c34432fcc509 Mon Sep 17 00:00:00 2001 From: Philipp Kunz Date: Sun, 14 Apr 2024 18:20:36 +0200 Subject: [PATCH] update tsconfig --- npmextra.json | 18 +++- package.json | 16 +++- readme.hints.md | 1 + readme.md | 225 +++++++++++++++++++++++++++--------------------- 4 files changed, 157 insertions(+), 103 deletions(-) create mode 100644 readme.hints.md diff --git a/npmextra.json b/npmextra.json index 88bbd11..b0cb507 100644 --- a/npmextra.json +++ b/npmextra.json @@ -5,17 +5,29 @@ "githost": "code.foss.global", "gitscope": "push.rocks", "gitrepo": "smartsocket", - "description": "easy and secure websocket communication", + "description": "Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.", "npmPackagename": "@push.rocks/smartsocket", "license": "MIT", - "projectDomain": "push.rocks" + "projectDomain": "push.rocks", + "keywords": [ + "websocket", + "communication", + "server", + "client", + "socket.io", + "authentication", + "reconnection", + "tagging", + "function routing", + "secure" + ] } }, "npmci": { "npmGlobalTools": [], "npmAccessLevel": "public" }, - "tsdocs": { + "tsdoc": { "legal": "\n## License and Legal Information\n\nThis repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. \n\n**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.\n\n### Trademarks\n\nThis project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.\n" } } \ No newline at end of file diff --git a/package.json b/package.json index 2b79332..223d2b5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@push.rocks/smartsocket", "version": "2.0.24", - "description": "easy and secure websocket communication", + "description": "Provides easy and secure websocket communication mechanisms, including server and client implementation, function call routing, connection management, and tagging.", "main": "dist_ts/index.js", "typings": "dist_ts/index.d.ts", "type": "module", @@ -60,5 +60,17 @@ ], "browserslist": [ "last 1 chrome versions" + ], + "keywords": [ + "websocket", + "communication", + "server", + "client", + "socket.io", + "authentication", + "reconnection", + "tagging", + "function routing", + "secure" ] -} +} \ No newline at end of file diff --git a/readme.hints.md b/readme.hints.md new file mode 100644 index 0000000..0519ecb --- /dev/null +++ b/readme.hints.md @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/readme.md b/readme.md index b5c01c0..43a0146 100644 --- a/readme.md +++ b/readme.md @@ -1,120 +1,149 @@ # @push.rocks/smartsocket easy and secure websocket communication -## Availabililty and Links -* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/smartsocket) -* [gitlab.com (source)](https://gitlab.com/push.rocks/smartsocket) -* [github.com (source mirror)](https://github.com/push.rocks/smartsocket) -* [docs (typedoc)](https://push.rocks.gitlab.io/smartsocket/) +## Install -## Status for master +To install @push.rocks/smartsocket, you can use npm or yarn as follows: -Status Category | Status Badge --- | -- -GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/smartsocket/badges/master/pipeline.svg)](https://lossless.cloud) -GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/smartsocket/badges/master/coverage.svg)](https://lossless.cloud) -npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/smartsocket)](https://lossless.cloud) -Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/smartsocket)](https://lossless.cloud) -TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud) -node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/) -Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud) -PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@push.rocks/smartsocket)](https://lossless.cloud) -PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/smartsocket)](https://lossless.cloud) -BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/smartsocket)](https://lossless.cloud) +```shell +npm install @push.rocks/smartsocket --save +``` +or +```shell +yarn add @push.rocks/smartsocket +``` ## Usage -Use TypeScript for best in class instellisense. +@push.rocks/smartsocket offers a robust solution for easy and secure WebSocket communication, utilizing Typescript for clean and maintainable code. Below are comprehensive examples covering various scenarios and features provided by the module. -Under the hood we use socket.io and shortid for managed data exchange. +### Getting Started -### Serverside +First, ensure you've installed the module as shown in the "Install" section. Once installed, you can start using @push.rocks/smartsocket in your project. + +### Setting Up a WebSocket Server + +To create a WebSocket server that clients can connect to: ```typescript -import * as smartsocket from 'smartsocket'; -import * as q from q; // q is a promise library +import { Smartsocket } from '@push.rocks/smartsocket'; -// The "Smartsocket" listens on a port and can receive new "SocketConnection" requests. -let mySmartsocket = new smartsocket.Smartsocket({ - port: 3000, // the port smartsocket will listen on +// Create a new instance of Smartsocket for the server. +const server = new Smartsocket({ alias: 'myServer' }); + +// Define a SocketFunction that clients can call +server.addSocketFunction({ + funcName: 'greet', + funcDef: async (data) => { + console.log(`Server received: ${data.message}`); + return { reply: `Hello, ${data.name}!` }; + } }); -// optional: -// run this with anothoer existing server like express -declare var someExpressServer; // read the express docs about how express actually works -mySmartsocket.setServer(someExpressServer); - -// A "SocketRole" can be referenced by "SocketFunction"s. -// All "SocketRequest"s carry authentication data for a specific "SocketRole". -// "SocketFunction"s know which "SocketRole"s are allowed to execute them -let mySocketRole = new smartsocket.SocketRole({ - name: 'someRoleName', - passwordHash: 'someHashedString', -}); - -// A "SocketFunction" executes a referenced function and passes in any data of the corresponding "SocketRequest". -// The referenced function must return a promise and resolve with data of type any. -// Any "SocketRequest" carries a unique identifier. If the referenced function's promise resolved any passed on argument will be returned to the requesting party -let testSocketFunction1 = new smartsocket.SocketFunction({ - funcName: 'testSocketFunction1', - funcDef: (data) => { - console.log('testSocketFunction1 executed successfully!'); - }, - allowedRoles: [mySocketRole], // all roles that have access to a specific function -}); - -// A "Smartsocket" exposes a .clientCall() that gets -// 1. the name of the "SocketFunction" on the client side -// 2. the data to pass in -// 3. And a target "SocketConnection" (there can be multiple connections at once) -// any unique id association is done internally -mySmartsocket.clientCall('restart', data, someTargetConnection).then((responseData) => {}); -``` - -#### Client side - -```typescript -import * as smartsocket from 'smartsocket'; - -// A "SmartsocketClient" is different from a "Smartsocket" in that it doesn't expose any public address. -// Thus any new "SocketConnection"s must be innitiated from a "SmartsocketClient". -let testSmartsocketClient = new smartsocket.SmartsocketClient({ - port: testConfig.port, - url: 'http://localhost', - password: 'testPassword', - alias: 'testClient1', - role: 'testRole1', -}); - -// You can .connect() and .disconnect() from a "Smartsocket" -testSmartsocketClient.connect().then(() => { - done(); -}); - -// The client can also specify "SocketFunction"s. It can also specify "SocketRole"s in case a client connects to multiple servers at once -let testSocketFunction2 = new smartsocket.SocketFunction({ - funcName: 'testSocketFunction2', - funcDef: (data) => {}, // the function to execute, has to return promise - allowedRoles: [], -}); - -// A "SmartsocketClient" can call functions on the serverside using .serverCall() analog to the "Smartsocket"'s .clientCall method. -mySmartsocketClient.serverCall('function', functionCallData).then((functionResponseData) => { - // the functionResponseData comes from the server... awesome, right? +// Start the Smartsocket server +server.start().then(() => { + console.log('WebSocket server is running...'); }); ``` -> **NOTE:** -> you can easily chain dependent requests on either the server or client side with promises. -> `data` is always a js object that you can design for your specific needs. -> It supports buffers for large binary data network exchange. +### Creating a WebSocket Client -## Contribution +Create a client that connects to the WebSocket server and interacts with it: -We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) +```typescript +import { SmartsocketClient } from '@push.rocks/smartsocket'; -For further information read the linked docs at the top of this readme. +// Create a SmartsocketClient instance and connect to the server +const client = new SmartsocketClient({ + url: 'ws://localhost', + port: 3000, + alias: 'myClient' +}); -## Legal -> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc) -| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) +client.connect().then(() => { + console.log('Connected to WebSocket server'); +}); + +// Define a function to call the server's 'greet' function +async function greetServer(name) { + const response = await client.serverCall('greet', { name: name, message: 'Hello!' }); + console.log(`Server replied: ${response.reply}`); +} + +// Use the function +greetServer('Alice'); +``` + +### Handling Disconnections and Reconnections + +@push.rocks/smartsocket provides mechanisms to handle client disconnections and attempt reconnections: + +```typescript +client.on('disconnect', () => { + console.log('Disconnected from server. Attempting to reconnect...'); + client.connect(); +}); +``` + +### Sending Binary Data + +The library supports the transmission of binary data efficiently: + +```typescript +import fs from 'fs'; + +// Function to send a binary file to the server +async function sendBinaryData(filePath) { + const fileBuffer = fs.readFileSync(filePath); + await client.serverCall('sendFile', { file: fileBuffer }); +} + +sendBinaryData('./path/to/your/file.png'); +``` + +### Securing Your WebSocket Communication + +@push.rocks/smartsocket leverages secure WebSocket (WSS) connections to ensure that data transferred between the client and server is encrypted. When setting up your Smartsocket server or client, use `wss://` in your URL to enable secure communication. + +### Advanced Usage + +#### Mesh Networking + +@push.rocks/smartsocket allows for the creation of complex mesh network configurations, enabling servers to communicate with other servers, forming a robust network with multiple nodes. + +#### Scaling with @push.rocks/smartsocket + +To scale your WebSocket services, you can utilize load balancers and ensure your @push.rocks/smartsocket instances are stateless to allow for horizontal scaling. + +### Conclusion + +This guide has covered how to set up basic WebSocket communication with @push.rocks/smartsocket, handle disconnections/reconnections, secure your communication, send binary data, and briefly touched on advanced concepts like mesh networking and scaling. + +For more detailed documentation, visit [the official @push.rocks/smartsocket GitLab repository](https://gitlab.com/pushrocks/smartsocket). + +Remember, WebSocket communication with @push.rocks/smartsocket is not only about sending and receiving messages. It's about creating a fast, reliable, and secure communication channel for your real-time applications. + +Happy coding! + +--- + +Please note, the documentation above is a starting point. Depending on the complexity and requirements of your application, you may need to explore more features and configurations provided by @push.rocks/smartsocket. Always refer to the official documentation for the most current information and best practices. + +## License and Legal Information + +This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository. + +**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. + +### Trademarks + +This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH. + +### Company Information + +Task Venture Capital GmbH +Registered at District court Bremen HRB 35230 HB, Germany + +For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. + +By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.