Compare commits

..

99 Commits

Author SHA1 Message Date
404f5ed3f3 v3.1.0 2025-12-02 13:54:32 +00:00
001f18ad3b feat(TypedSocket): Add SmartServe integration to TypedSocket, support SmartServe connections and tagging; update dependencies and docs; remove GitLab CI config 2025-12-02 13:54:32 +00:00
2e4adba867 3.0.1 2024-04-18 21:49:13 +02:00
a6530e9752 fix(core): update 2024-04-18 21:49:13 +02:00
7163c1dc67 update documentation 2024-04-14 19:01:25 +02:00
c2f4efd33d 3.0.0 2023-08-06 16:52:04 +02:00
bc7a828124 BREAKING CHANGE(core): update 2023-08-06 16:52:03 +02:00
f62497ce48 2.0.28 2023-08-06 16:37:40 +02:00
64e5f30bad fix(core): update 2023-08-06 16:37:39 +02:00
1b41d5e3ad 2.0.27 2023-08-05 12:00:28 +02:00
c5954aa880 fix(core): update 2023-08-05 12:00:27 +02:00
b58d8084e9 2.0.26 2023-08-05 11:46:40 +02:00
f765e60e1f fix(core): update 2023-08-05 11:46:39 +02:00
b726669c4b 2.0.25 2023-08-04 16:22:40 +02:00
4f0066b5ca fix(core): update 2023-08-04 16:22:39 +02:00
0edc903900 2.0.24 2023-03-29 19:02:10 +02:00
fa41192377 fix(core): update 2023-03-29 19:02:10 +02:00
725e3c65c6 2.0.23 2023-03-29 16:29:58 +02:00
4e9108f7df fix(core): update 2023-03-29 16:29:58 +02:00
420d634e83 2.0.22 2023-03-29 13:47:03 +02:00
eb596e5dd8 fix(core): update 2023-03-29 13:47:03 +02:00
5748bd8280 2.0.21 2023-03-29 13:45:34 +02:00
4e8ea21df2 fix(core): update 2023-03-29 13:45:33 +02:00
6f4be3baaa 2.0.20 2023-03-20 19:23:20 +01:00
a484060888 fix(core): update 2023-03-20 19:23:20 +01:00
c1b15daaca 2.0.19 2023-03-20 17:06:33 +01:00
f9397feaf0 fix(core): update 2023-03-20 17:06:33 +01:00
889ec9c8ec 2.0.18 2022-12-29 12:17:59 +01:00
5d460cf002 fix(core): update 2022-12-29 12:17:58 +01:00
5e6ec0d311 2.0.17 2022-12-28 20:31:03 +01:00
dd834590cc fix(core): update 2022-12-28 20:31:03 +01:00
96b7354dae 2.0.16 2022-12-28 18:54:57 +01:00
3a5533c4fe fix(core): update 2022-12-28 18:54:57 +01:00
1f5f84763d 2.0.15 2022-12-28 15:15:19 +01:00
6474112275 fix(core): update 2022-12-28 15:15:19 +01:00
a46c0cf395 2.0.14 2022-12-28 15:14:48 +01:00
8be5c352f4 fix(core): update 2022-12-28 15:14:48 +01:00
caaf947a46 2.0.13 2022-12-28 15:05:53 +01:00
2ec88494be fix(core): update 2022-12-28 15:05:53 +01:00
b80346d742 2.0.12 2022-10-26 22:39:40 +02:00
aced21a968 fix(core): update 2022-10-26 22:39:39 +02:00
fa40e3a5dc 2.0.11 2022-10-26 18:59:50 +02:00
9bb0008381 fix(core): update 2022-10-26 18:59:49 +02:00
67bbea8811 2.0.10 2022-10-26 14:23:14 +02:00
dc826cb65a fix(core): update 2022-10-26 14:23:14 +02:00
1266a814c6 2.0.9 2022-10-26 11:00:07 +02:00
25a7397548 fix(core): update 2022-10-26 11:00:06 +02:00
5009bec70c 2.0.8 2022-10-26 10:55:09 +02:00
d8d7b135f7 fix(core): update 2022-10-26 10:55:08 +02:00
9738d88ec7 2.0.7 2022-10-26 10:54:37 +02:00
9d7f433685 fix(core): update 2022-10-26 10:54:36 +02:00
fc1124fb16 2.0.6 2022-10-26 10:54:19 +02:00
5e5f493dfa fix(core): update 2022-10-26 10:54:18 +02:00
899a46f9de 2.0.5 2022-08-02 10:21:16 +02:00
1412a06f4c fix(core): update 2022-08-02 10:21:15 +02:00
51e6c5cf0e 2.0.4 2022-05-13 08:14:10 +02:00
8d7eb3ff5f fix(core): update 2022-05-13 08:14:09 +02:00
a82f8ccc26 2.0.3 2022-03-29 15:38:38 +02:00
d934f4b53b fix(core): update 2022-03-29 15:38:37 +02:00
54b8a692ba 2.0.2 2022-03-25 00:42:50 +01:00
2f39b5662d fix(core): update 2022-03-25 00:42:50 +01:00
5b9e785159 2.0.1 2022-03-25 00:31:10 +01:00
a5bca90eeb fix(core): update 2022-03-25 00:31:10 +01:00
244016faed 2.0.0 2022-03-24 23:09:36 +01:00
61719769a0 1.0.27 2022-03-24 22:46:09 +01:00
6e2855cf3c fix(core): update 2022-03-24 22:46:08 +01:00
916052ef0b 1.0.26 2022-03-08 00:14:41 +01:00
2f51e10fc4 fix(core): update 2022-03-08 00:14:40 +01:00
6e2e2768e2 1.0.25 2022-03-08 00:03:42 +01:00
4c5abc89b8 fix(core): update 2022-03-08 00:03:42 +01:00
5911d829f9 1.0.24 2022-01-20 19:23:54 +01:00
eac735a691 fix(core): update 2022-01-20 19:23:53 +01:00
4af7164a58 1.0.23 2022-01-20 17:44:51 +01:00
006073cbc8 fix(core): update 2022-01-20 17:44:50 +01:00
7d8b41a5a6 1.0.22 2022-01-19 19:17:23 +01:00
acca64fa31 fix(core): update 2022-01-19 19:17:22 +01:00
1e570813a3 1.0.21 2021-11-10 17:35:55 +01:00
0199e8ef17 fix(core): update 2021-11-10 17:35:55 +01:00
68def29c80 1.0.20 2021-10-23 00:27:47 +02:00
106eb12a7f fix(core): update 2021-10-23 00:27:46 +02:00
5b868f1259 1.0.19 2021-10-22 21:09:43 +02:00
952835e46a fix(core): update 2021-10-22 21:09:42 +02:00
5aa8048ce8 1.0.18 2021-07-20 11:09:23 +02:00
48112f97ce fix(core): update 2021-07-20 11:09:22 +02:00
57a10080b5 1.0.17 2021-07-20 02:44:14 +02:00
7bdac2b89d 1.0.16 2021-07-20 02:04:46 +02:00
6c49870dd6 fix(core): update 2021-07-20 02:04:45 +02:00
a2db05bfe3 1.0.15 2021-02-02 00:11:33 +00:00
69668731be fix(core): update 2021-02-02 00:11:32 +00:00
e586843d81 1.0.14 2021-01-28 12:58:42 +00:00
fef1ae338a fix(core): update 2021-01-28 12:58:42 +00:00
969b2d6686 1.0.13 2021-01-28 02:12:22 +00:00
f4d820d37e fix(core): update 2021-01-28 02:12:22 +00:00
c08acd076e 1.0.12 2021-01-23 06:04:02 +00:00
c968de37d1 fix(core): update 2021-01-23 06:04:02 +00:00
5b8f7514f4 1.0.11 2021-01-23 05:14:30 +00:00
53874a7772 fix(core): update 2021-01-23 05:14:29 +00:00
479cf60239 1.0.10 2021-01-23 04:51:49 +00:00
825a264327 fix(core): update 2021-01-23 04:51:48 +00:00
17 changed files with 13102 additions and 11405 deletions

View File

@@ -1,137 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

24
.vscode/launch.json vendored
View File

@@ -2,28 +2,10 @@
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
"type": "node-terminal"
}
]
}

47
changelog.md Normal file
View File

@@ -0,0 +1,47 @@
# Changelog
## 2025-12-02 - 3.1.0 - feat(TypedSocket)
Add SmartServe integration to TypedSocket, support SmartServe connections and tagging; update dependencies and docs; remove GitLab CI config
- Add TypedSocket.fromSmartServe(smartServe, typedRouter) to bind TypedSocket to an existing SmartServe instance for native WebSocket handling.
- Introduce ISmartServeConnectionWrapper and wrapSmartServePeer to provide tag compatibility between SmartServe (Set<string>) and TypedSocket (id/payload). Tag payloads are stored in peer.data with '__typedsocket_tag__' prefix.
- Server-initiated requests in SmartServe mode use TypedRouter.fireEventInterestMap to correlate requests and responses asynchronously.
- Extend createTypedRequest, findAllTargetConnections, findTargetConnection, findAllTargetConnectionsByTag and findTargetConnectionByTag to support both Smartsocket and SmartServe backends (via wrappers).
- eventSubject: Emit a warning and return a new Subject in SmartServe mode (SmartServe lifecycle/events should be consumed via SmartServe hooks).
- stop(): In SmartServe mode TypedSocket clears internal wrappers but does not stop SmartServe (SmartServe lifecycle is managed externally).
- Add optional peer dependency @push.rocks/smartserve and expose type-only imports in ts/typedsocket.plugins.ts.
- Bump several devDependencies and runtime dependencies to newer versions (tsbuild, tsbundle, tsrun, tstest, smartenv, smartserve, smartjson, smartrx, smartsocket, smartstring, smarturl).
- Update README and readme.hints with SmartServe integration docs and examples.
- Remove .gitlab-ci.yml (CI configuration removed).
## 2024-04-18 - 3.0.1 - patch
Small patch release.
- Version bump to 3.0.1.
- No additional details provided in commits.
## 2024-04-18 - 3.0.0 - core
Major 3.0.0 release with core updates and documentation improvements.
- Core fixes and updates applied.
- Documentation updated (commit dated 2024-04-14).
- General maintenance and polishing for the 3.x line.
## 2023-08-06 - 2.0.28 - core (BREAKING CHANGE)
Breaking change in core introduced in 2.0.28; important compatibility considerations.
- BREAKING CHANGE(core): update — review integration points before upgrading.
- This capstone release follows a series of patch releases addressing stability and core behavior.
## 2022-03-24 - 2.0.0 - core
Introduction of the 2.x stable line and subsequent patch series.
- 2.0.0 initial release of the 2.x series.
- Follow-up patch releases (2.0.1 through 2.0.27) contain numerous "fix(core): update" changes — ongoing bug fixes, stability improvements, and small core adjustments across 20222023.
- Users upgrading from 1.x should review 2.x changes and the 2.0.28 breaking change above.
## 2020-12-26 - 1.0.2 - core
Initial implemented functionality and the start of 1.x maintenance.
- fix(core): implement basic functionality — initial usable feature set implemented in 1.0.2.
- Subsequent 1.0.3 through 1.0.27 releases (20202022) included ongoing fixes and minor updates to stabilize the 1.x line.

View File

@@ -2,17 +2,28 @@
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "apiglobal",
"githost": "code.foss.global",
"gitscope": "api.global",
"gitrepo": "typedsocket",
"shortDescription": "a typedrequest extension supporting websockets",
"npmPackagename": "@apiglobal/typedsocket",
"description": "A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.",
"npmPackagename": "@api.global/typedsocket",
"license": "MIT",
"projectDomain": "api.global"
"projectDomain": "api.global",
"keywords": [
"WebSocket",
"Type Safety",
"Real-time Communication",
"Client-Server Architecture",
"TypeScript",
"Networking"
]
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"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"
}
}

11094
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,32 +1,45 @@
{
"name": "@apiglobal/typedsocket",
"version": "1.0.9",
"name": "@api.global/typedsocket",
"version": "3.1.0",
"private": false,
"description": "a typedrequest extension supporting websockets",
"description": "A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/ --web)",
"build": "(tsbuild --web)"
"build": "(tsbuild --web --allowimplicitany --skiplibcheck)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.25",
"@gitzone/tsbundle": "^1.0.78",
"@gitzone/tstest": "^1.0.44",
"@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.14.22",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0"
"@git.zone/tsbuild": "^3.1.2",
"@git.zone/tsbundle": "^2.6.2",
"@git.zone/tsrun": "^2.0.0",
"@git.zone/tstest": "^3.1.3",
"@push.rocks/smartenv": "^6.0.0",
"@push.rocks/smartserve": "^1.1.0",
"@push.rocks/tapbundle": "^6.0.3",
"@types/node": "^24.10.1"
},
"dependencies": {
"@apiglobal/typedrequest": "^1.0.56",
"@apiglobal/typedrequest-interfaces": "^1.0.15",
"@pushrocks/isohash": "^1.0.2",
"@pushrocks/smartexpress": "^3.0.100",
"@pushrocks/smartsocket": "^1.2.1",
"@pushrocks/smartstring": "^3.0.24"
"@api.global/typedrequest": "^3.1.10",
"@api.global/typedrequest-interfaces": "^3.0.19",
"@push.rocks/isohash": "^2.0.1",
"@push.rocks/smartjson": "^5.2.0",
"@push.rocks/smartrx": "^3.0.10",
"@push.rocks/smartsocket": "^2.1.0",
"@push.rocks/smartstring": "^4.1.0",
"@push.rocks/smarturl": "^3.1.0"
},
"peerDependencies": {
"@push.rocks/smartserve": ">=1.0.0"
},
"peerDependenciesMeta": {
"@push.rocks/smartserve": {
"optional": true
}
},
"browserslist": [
"last 1 chrome versions"
@@ -42,5 +55,13 @@
"cli.js",
"npmextra.json",
"readme.md"
],
"keywords": [
"WebSocket",
"Type Safety",
"Real-time Communication",
"Client-Server Architecture",
"TypeScript",
"Networking"
]
}

12308
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

21
readme.hints.md Normal file
View File

@@ -0,0 +1,21 @@
# TypedSocket Hints
## SmartServe Integration (Added v3.1.0)
TypedSocket now supports SmartServe as an alternative WebSocket backend via `TypedSocket.fromSmartServe()`.
### Key Differences from Smartsocket Mode
1. **Tag System**: SmartServe uses `Set<string>` for tags, while Smartsocket uses `{id, payload}`. The wrapper stores payloads in `peer.data` with `__typedsocket_tag__` prefix.
2. **Request/Response**: Uses TypedRouter's `fireEventInterestMap` for async correlation when sending server-initiated requests.
3. **Lifecycle**: SmartServe manages WebSocket lifecycle. `typedSocket.stop()` only clears internal state.
4. **eventSubject**: Not fully supported in SmartServe mode - use SmartServe's `onConnectionOpen`/`onConnectionClose` hooks instead.
### Files Modified for SmartServe Support
- `ts/typedsocket.classes.typedsocket.ts` - Main implementation
- `ts/typedsocket.plugins.ts` - Type imports
- `package.json` - Optional peer dependency

329
readme.md
View File

@@ -1,43 +1,312 @@
# @apiglobal/typedsocket
a typedrequest extension supporting websockets
# @api.global/typedsocket
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiglobal/typedsocket)
* [gitlab.com (source)](https://gitlab.com/apiglobal/typedsocket)
* [github.com (source mirror)](https://github.com/apiglobal/typedsocket)
* [docs (typedoc)](https://apiglobal.gitlab.io/typedsocket/)
A TypeScript library for creating typed WebSocket connections with bi-directional communication support. Extends `@api.global/typedrequest` to bring type-safe request/response patterns to WebSocket connections.
## Status for master
## Issue Reporting and Security
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/apiglobal/typedsocket/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/apiglobal/typedsocket/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiglobal/typedsocket)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/apiglobal/typedsocket)](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/@apiglobal/typedsocket)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiglobal/typedsocket)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiglobal/typedsocket)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
## Features
- 🔒 **Full Type Safety** - Leverages TypeScript for compile-time checking of all request/response payloads
- 🔄 **Bi-directional Communication** - Both server and client can initiate requests
- 🔌 **Auto-reconnect** - Client automatically reconnects on connection loss
- 🏷️ **Connection Tagging** - Tag and filter connections for targeted messaging
- 🌐 **Browser Compatible** - Works in both Node.js and browser environments
- 🔗 **SmartExpress Integration** - Optional integration with existing SmartExpress servers
- 🚀 **SmartServe Integration** - Native support for SmartServe's WebSocket handling
## Install
```bash
npm install @api.global/typedsocket
```
Or with pnpm:
```bash
pnpm add @api.global/typedsocket
```
## Usage
Use TypeScript for best in class intellisense.
### Prerequisites
TypedSocket is the typedrequest you love, just in a bidirectional way.
- TypeScript project setup
- Basic understanding of async/await patterns
- Familiarity with `@api.global/typedrequest` concepts
See the following examples from our test for reference:
### Define Your Request Interface
## Contribution
First, define the typed request interface that both client and server will use:
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 * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
For further information read the linked docs at the top of this readme.
interface IGreetingRequest extends typedrequestInterfaces.implementsTR<
typedrequestInterfaces.ITypedRequest,
IGreetingRequest
> {
method: 'greet';
request: {
name: string;
};
response: {
message: string;
};
}
```
> MIT licensed | **&copy;** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
### Server Setup
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)
Create a WebSocket server that handles typed requests:
```typescript
import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';
// Create the router and add handlers
const typedRouter = new typedrequest.TypedRouter();
typedRouter.addTypedHandler<IGreetingRequest>(
new typedrequest.TypedHandler('greet', async (requestData) => {
return {
message: `Hello, ${requestData.name}! 👋`,
};
})
);
// Start the TypedSocket server (defaults to port 3000)
const server = await TypedSocket.createServer(typedRouter);
```
#### Integration with SmartExpress
If you have an existing SmartExpress server, you can attach TypedSocket to it:
```typescript
import { TypedSocket } from '@api.global/typedsocket';
import * as smartexpress from '@push.rocks/smartexpress';
const smartExpressServer = new smartexpress.Server({ port: 8080 });
await smartExpressServer.start();
const server = await TypedSocket.createServer(typedRouter, smartExpressServer);
```
#### Integration with SmartServe
For SmartServe-based applications, use `fromSmartServe()` for native integration:
```typescript
import { TypedSocket } from '@api.global/typedsocket';
import { SmartServe } from '@push.rocks/smartserve';
import * as typedrequest from '@api.global/typedrequest';
const typedRouter = new typedrequest.TypedRouter();
// Add handlers for client-to-server requests
typedRouter.addTypedHandler<IGreetingRequest>(
new typedrequest.TypedHandler('greet', async (requestData) => {
return { message: `Hello, ${requestData.name}!` };
})
);
// Create SmartServe with typedRouter in websocket options
const smartServe = new SmartServe({
port: 3000,
websocket: {
typedRouter,
onConnectionOpen: (peer) => {
// Tag connections for later filtering
peer.tags.add('client');
}
}
});
await smartServe.start();
// Create TypedSocket bound to SmartServe
const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter);
// Push notifications to tagged clients
const clients = await typedSocket.findAllTargetConnectionsByTag('client');
for (const client of clients) {
const request = typedSocket.createTypedRequest<INotifyRequest>('notify', client);
await request.fire({ message: 'Hello from server!' });
}
```
> **Note:** When using SmartServe, the WebSocket transport is managed by SmartServe. TypedSocket acts as a convenience layer for finding connections and sending server-initiated requests.
### Client Setup
Connect to the WebSocket server from a client:
```typescript
import { TypedSocket } from '@api.global/typedsocket';
import * as typedrequest from '@api.global/typedrequest';
// Create a router for handling server-initiated requests (if needed)
const clientRouter = new typedrequest.TypedRouter();
// Connect to the server
const client = await TypedSocket.createClient(
clientRouter,
'http://localhost:3000'
);
```
#### Using Window Location (Browser)
In browser environments, you can automatically use the current page's origin:
```typescript
const client = await TypedSocket.createClient(
clientRouter,
TypedSocket.useWindowLocationOriginUrl()
);
```
### Sending Requests
#### Client to Server
```typescript
const request = client.createTypedRequest<IGreetingRequest>('greet');
const response = await request.fire({
name: 'World',
});
console.log(response.message); // "Hello, World! 👋"
```
#### Server to Client
The server can also initiate requests to connected clients:
```typescript
// When only one client is connected, it's automatically selected
const request = server.createTypedRequest<IGreetingRequest>('greet');
const response = await request.fire({
name: 'Client',
});
// For multiple clients, specify the target connection
const connection = await server.findTargetConnection(async (conn) => {
// Your filter logic here
return true;
});
const targetedRequest = server.createTypedRequest<IGreetingRequest>('greet', connection);
```
### Connection Tagging
Tag connections for organized, targeted communication:
```typescript
// Client side: add a tag
interface IUserTag extends typedrequestInterfaces.ITag {
name: 'userRole';
payload: 'admin' | 'user' | 'guest';
}
client.addTag<IUserTag>('userRole', 'admin');
```
```typescript
// Server side: find connections by tag
const adminConnections = await server.findAllTargetConnectionsByTag<IUserTag>(
'userRole',
'admin'
);
// Send to all admins
for (const conn of adminConnections) {
const request = server.createTypedRequest<INotificationRequest>('notify', conn);
await request.fire({ message: 'Admin notification' });
}
// Find a single connection
const firstAdmin = await server.findTargetConnectionByTag<IUserTag>('userRole', 'admin');
```
### Event Handling
Subscribe to connection status events:
```typescript
client.eventSubject.subscribe((status) => {
console.log('Connection status:', status);
});
server.eventSubject.subscribe((status) => {
console.log('Server connection event:', status);
});
```
### Cleanup
Properly close connections when done:
```typescript
// Client
await client.stop();
// Server
await server.stop();
```
## API Reference
### TypedSocket
#### Static Methods
| Method | Description |
|--------|-------------|
| `createServer(router, smartExpressServer?)` | Creates a WebSocket server. Optionally attach to an existing SmartExpress server. |
| `createClient(router, serverUrl, alias?)` | Creates a WebSocket client that connects to the specified server URL. |
| `fromSmartServe(smartServe, router)` | Creates a TypedSocket bound to an existing SmartServe instance. |
| `useWindowLocationOriginUrl()` | Returns the current window location origin (browser only). |
#### Instance Properties
| Property | Description |
|----------|-------------|
| `side` | Whether this instance is a `'server'` or `'client'`. |
| `typedrouter` | The TypedRouter instance handling requests. |
| `eventSubject` | RxJS Subject for connection status events. |
#### Instance Methods
| Method | Description |
|--------|-------------|
| `createTypedRequest(method, targetConnection?)` | Creates a typed request for the specified method. |
| `addTag(name, payload)` | Adds a tag to the client connection (client-side only). |
| `findAllTargetConnections(filterFn)` | Finds all connections matching the filter (server-side only). |
| `findTargetConnection(filterFn)` | Finds the first connection matching the filter (server-side only). |
| `findAllTargetConnectionsByTag(key, payload?)` | Finds all connections with the specified tag. |
| `findTargetConnectionByTag(key, payload?)` | Finds the first connection with the specified tag. |
| `stop()` | Closes the WebSocket connection. |
## License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
### Company Information
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or 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.

View File

@@ -1,6 +1,6 @@
import { tap, expect } from '@pushrocks/tapbundle';
import { tap, expect } from '@push.rocks/tapbundle';
import * as typedsocket from '../ts/index';
import * as typedsocket from '../ts/index.js';
tap.test('should create a client', async () => {
console.log('Browser test') // TODO: implement browser tests

View File

@@ -1,21 +1,21 @@
import { expect, tap } from '@pushrocks/tapbundle';
import * as typedrequest from '@apiglobal/typedrequest';
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
import { expect, tap } from '@push.rocks/tapbundle';
import * as typedrequest from '@api.global/typedrequest';
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
import * as typedsocket from '../ts/index';
import { request } from 'http';
import * as typedsocket from '../ts/index.js';
interface IRequest_Client_Server extends typedrequestInterfaces.implementsTR<
typedrequestInterfaces.ITypedRequest,
IRequest_Client_Server
> {
interface IRequest_Client_Server
extends typedrequestInterfaces.implementsTR<
typedrequestInterfaces.ITypedRequest,
IRequest_Client_Server
> {
method: 'sayhi';
request: {
greeting: string;
};
response: {
answer: string
}
answer: string;
};
}
let testTypedSocketServer: typedsocket.TypedSocket;
@@ -24,38 +24,52 @@ let testTypedSocketClient: typedsocket.TypedSocket;
const testTypedRouter = new typedrequest.TypedRouter();
tap.test('should add some handlers', async () => {
testTypedRouter.addTypedHandler<IRequest_Client_Server>(new typedrequest.TypedHandler('sayhi', async requestData => {
return {
answer: `ok, got it : ${requestData.greeting}`
}
}));
})
testTypedRouter.addTypedHandler<IRequest_Client_Server>(
new typedrequest.TypedHandler('sayhi', async (requestData) => {
return {
answer: `ok, got it : ${requestData.greeting}`,
};
})
);
});
tap.test('should create Server and Client', async (tools) => {
testTypedSocketServer = await typedsocket.TypedSocket.createServer(testTypedRouter);
testTypedSocketClient = await typedsocket.TypedSocket.createClient(testTypedRouter, 'http://localhost');
testTypedSocketClient = await typedsocket.TypedSocket.createClient(
testTypedRouter,
'http://localhost:3000'
);
console.log('test: waiting 5 seconds');
await tools.delayFor(5000);
await testTypedSocketServer.stop();
// lets create another server
testTypedSocketServer = await typedsocket.TypedSocket.createServer(testTypedRouter);
// lets see if auto reconnect works
console.log('test: waiting 21 seconds for reconnect');
await tools.delayFor(21000);
});
tap.test('should process messages from both sides', async () => {
const myServerSideTypedRequest = testTypedSocketServer.createTypedRequest<IRequest_Client_Server>('sayhi');
const myClientSideTypedRequest = testTypedSocketClient.createTypedRequest<IRequest_Client_Server>('sayhi');
const myServerSideTypedRequest =
testTypedSocketServer.createTypedRequest<IRequest_Client_Server>('sayhi');
const myClientSideTypedRequest =
testTypedSocketClient.createTypedRequest<IRequest_Client_Server>('sayhi');
const response = await myClientSideTypedRequest.fire({
greeting: 'that is a greeting from the client'
greeting: 'that is a greeting from the client',
});
console.log(response);
const response2 = await myServerSideTypedRequest.fire({
greeting: 'that is a greeting from the server'
greeting: 'that is a greeting from the server',
});
console.log(response2);
})
});
tap.test('should run without problems for a little bit', async tools => {
await tools.delayFor(5000);
})
tap.test('should disconnect', async () => {
tap.test('should disconnect', async (tools) => {
await testTypedSocketClient.stop();
await testTypedSocketServer.stop();
})
tools.delayFor(1000).then(() => process.exit(0));
});
tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @push.rocks/commitinfo
*/
export const commitinfo = {
name: '@api.global/typedsocket',
version: '3.1.0',
description: 'A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.'
}

View File

@@ -1 +1 @@
export * from './typedsocket.classes.typedsocket';
export * from './typedsocket.classes.typedsocket.js';

View File

@@ -1,9 +1,36 @@
import * as plugins from './typedsocket.plugins';
import type * as smartexpress from '@pushrocks/smartexpress';
import * as plugins from './typedsocket.plugins.js';
const publicRoleName = 'publicRoleName';
const publicRolePass = 'publicRolePass';
export type TTypedSocketSide = 'server' | 'client';
/**
* Wrapper for SmartServe's IWebSocketPeer to provide tag compatibility
* SmartServe uses Set<string> for tags, while TypedSocket uses {id, payload} format
*/
export interface ISmartServeConnectionWrapper {
peer: plugins.IWebSocketPeer;
getTagById(tagId: string): Promise<{ id: string; payload: any } | undefined>;
}
/**
* Creates a wrapper around IWebSocketPeer for tag compatibility
*/
function wrapSmartServePeer(peer: plugins.IWebSocketPeer): ISmartServeConnectionWrapper {
const TAG_PREFIX = '__typedsocket_tag__';
return {
peer,
async getTagById(tagId: string): Promise<{ id: string; payload: any } | undefined> {
if (!peer.tags.has(tagId)) {
return undefined;
}
const payload = peer.data.get(`${TAG_PREFIX}${tagId}`);
return { id: tagId, payload };
},
};
}
export class TypedSocket {
// STATIC
/**
@@ -12,29 +39,26 @@ export class TypedSocket {
*/
public static async createServer(
typedrouterArg: plugins.typedrequest.TypedRouter,
smartexpressServerArg?: smartexpress.Server
smartexpressServerArg?: any
): Promise<TypedSocket> {
const smartsocketServer = new plugins.smartsocket.Smartsocket({
alias: 'typedsocketServer',
port: 3000,
});
if (smartexpressServerArg) {
smartsocketServer.setExternalServer('smartexpress', smartexpressServerArg);
}
const publicRole = new plugins.smartsocket.SocketRole({
name: publicRoleName,
passwordHash: await plugins.isohash.sha256FromString(publicRolePass),
});
smartsocketServer.addSocketRoles([publicRole]);
smartsocketServer.socketFunctions.add(
new plugins.smartsocket.SocketFunction({
funcName: 'processMessage',
allowedRoles: [publicRole],
funcDef: async (dataArg, socketConnectionArg) => {
return typedrouterArg.routeAndAddResponse(dataArg);
},
})
);
const typedsocket = new TypedSocket(
'server',
typedrouterArg,
async <T extends plugins.typedrequestInterfaces.ITypedRequest>(
dataArg: T,
@@ -47,21 +71,20 @@ export class TypedSocket {
);
targetConnectionArg = smartsocketServer.socketConnections.getArray()[0];
} else {
throw new Error('you need to specify the wanted targetConnection');
throw new Error(
'you need to specify the wanted targetConnection. Currently no target is selectable automatically.'
);
}
}
const response: T = await smartsocketServer.clientCall(
const response: T = (await smartsocketServer.clientCall(
'processMessage',
dataArg,
targetConnectionArg
) as any;
)) as any;
return response;
},
smartsocketServer
);
if (smartexpressServerArg && smartexpressServerArg.serverStatus !== 'running') {
await smartexpressServerArg.start()
}
await smartsocketServer.start();
return typedsocket;
@@ -74,64 +97,188 @@ export class TypedSocket {
): Promise<TypedSocket> {
const domain = new plugins.smartstring.Domain(serverUrlArg);
const smartsocketClient = new plugins.smartsocket.SmartsocketClient({
const socketOptions: plugins.smartsocket.ISmartsocketClientOptions = {
alias: aliasArg,
role: publicRoleName,
password: publicRolePass,
port: domain.port || 3000,
url: `${domain.nodeParsedUrl.protocol}//${domain.nodeParsedUrl.host}`,
url: `${domain.nodeParsedUrl.protocol}//${domain.nodeParsedUrl.hostname}`,
autoReconnect: true,
});
};
console.log(`starting typedsocket with the following settings:`);
console.log(socketOptions);
const smartsocketClient = new plugins.smartsocket.SmartsocketClient(socketOptions);
smartsocketClient.addSocketFunction(
new plugins.smartsocket.SocketFunction({
funcName: 'processMessage',
allowedRoles: [],
funcDef: async (dataArg, socketConnectionArg) => {
return typedrouterArg.routeAndAddResponse(dataArg);
},
})
);
const typedsocket = new TypedSocket(
'client',
typedrouterArg,
async <T extends plugins.typedrequestInterfaces.ITypedRequest>(dataArg: T): Promise<T> => {
const response: T = (smartsocketClient.serverCall('processMessage', dataArg) as any) as T;
const response: T = smartsocketClient.serverCall('processMessage', dataArg) as any as T;
return response;
},
smartsocketClient
);
console.log(`typedsocket triggering smartsocket to connect...`);
const before = Date.now();
await smartsocketClient.connect();
console.log(`typedsocket triggered smartsocket connected in ${Date.now() - before}ms!!!`)
return typedsocket;
}
public static useWindowLocationOriginUrl = () => {
const windowLocationResult = plugins.smarturl.Smarturl.createFromUrl(globalThis.location.origin).toString();
return windowLocationResult;
}
/**
* Creates a TypedSocket server from an existing SmartServe instance.
* Use this when you want TypedSocket to work with SmartServe's WebSocket handling.
*
* @param smartServeArg - SmartServe instance with typedRouter configured in websocket options
* @param typedRouterArg - TypedRouter for handling requests (must match SmartServe's typedRouter)
*
* @example
* ```typescript
* const typedRouter = new TypedRouter();
* const smartServe = new SmartServe({
* port: 3000,
* websocket: {
* typedRouter,
* onConnectionOpen: (peer) => peer.tags.add('client')
* }
* });
* await smartServe.start();
* const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter);
* ```
*/
public static fromSmartServe(
smartServeArg: plugins.SmartServe,
typedRouterArg: plugins.typedrequest.TypedRouter
): TypedSocket {
const connectionWrappers = new Map<string, ISmartServeConnectionWrapper>();
// Create the postMethod for server-initiated requests
const postMethod = async <T extends plugins.typedrequestInterfaces.ITypedRequest>(
dataArg: T,
targetConnectionArg?: ISmartServeConnectionWrapper
): Promise<T> => {
if (!targetConnectionArg) {
const allConnections = smartServeArg.getWebSocketConnections();
if (allConnections.length === 1) {
console.log(
'Since no targetConnection was supplied and there is only one active one present, choosing that one automatically'
);
const peer = allConnections[0];
let wrapper = connectionWrappers.get(peer.id);
if (!wrapper) {
wrapper = wrapSmartServePeer(peer);
connectionWrappers.set(peer.id, wrapper);
}
targetConnectionArg = wrapper;
} else if (allConnections.length === 0) {
throw new Error('No WebSocket connections available');
} else {
throw new Error(
'you need to specify the wanted targetConnection. Currently no target is selectable automatically.'
);
}
}
// Register interest for the response using correlation ID
const interest = await typedRouterArg.fireEventInterestMap.addInterest(
dataArg.correlation.id,
dataArg
);
// Send the request to the client
targetConnectionArg.peer.send(plugins.smartjson.stringify(dataArg));
// Wait for the response (TypedRouter will fulfill via routeAndAddResponse when response arrives)
const response = await interest.interestFullfilled as T;
return response;
};
const typedSocket = new TypedSocket(
'server',
typedRouterArg,
postMethod as any,
null as any // No smartsocket server/client when using SmartServe
);
typedSocket.smartServeRef = smartServeArg;
typedSocket.smartServeConnectionWrappers = connectionWrappers;
return typedSocket;
}
// INSTANCE
public side: TTypedSocketSide;
public typedrouter: plugins.typedrequest.TypedRouter;
// SmartServe mode properties
private smartServeRef?: plugins.SmartServe;
private smartServeConnectionWrappers: Map<string, ISmartServeConnectionWrapper> = new Map();
public get eventSubject(): plugins.smartrx.rxjs.Subject<plugins.smartsocket.TConnectionStatus> {
if (this.smartServeRef) {
// SmartServe doesn't provide an eventSubject, return a new Subject
// In SmartServe mode, connection events are handled via onConnectionOpen/onConnectionClose hooks
console.warn('eventSubject is not fully supported in SmartServe mode. Use SmartServe hooks instead.');
return new plugins.smartrx.rxjs.Subject();
}
return this.socketServerOrClient.eventSubject;
}
private postMethod: plugins.typedrequest.IPostMethod &
((
typedRequestPostObject: plugins.typedrequestInterfaces.ITypedRequest,
socketConnectionArg?: plugins.smartsocket.SocketConnection
socketConnectionArg?: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper
) => Promise<plugins.typedrequestInterfaces.ITypedRequest>);
private socketServerOrClient: plugins.smartsocket.Smartsocket | plugins.smartsocket.SmartsocketClient;
private socketServerOrClient:
| plugins.smartsocket.Smartsocket
| plugins.smartsocket.SmartsocketClient;
constructor(
sideArg: TTypedSocketSide,
typedrouterArg: plugins.typedrequest.TypedRouter,
postMethodArg: plugins.typedrequest.IPostMethod,
socketServerOrClientArg: plugins.smartsocket.Smartsocket | plugins.smartsocket.SmartsocketClient
) {
this.side = sideArg;
this.typedrouter = typedrouterArg;
this.postMethod = postMethodArg;
this.socketServerOrClient = socketServerOrClientArg;
}
public addTag<T extends plugins.typedrequestInterfaces.ITag = any>(
nameArg: T['name'],
payloadArg: T['payload']
) {
if (
this.side === 'client' &&
this.socketServerOrClient instanceof plugins.smartsocket.SmartsocketClient
) {
this.socketServerOrClient.socketConnection.addTag({
id: nameArg,
payload: payloadArg,
});
} else {
throw new Error('tagging is only supported on clients');
}
}
public createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(
methodName: T['method'],
targetConnection?: plugins.smartsocket.SocketConnection
targetConnection?: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper
): plugins.typedrequest.TypedRequest<T> {
const typedrequest = new plugins.typedrequest.TypedRequest<T>(
new plugins.typedrequest.TypedTarget({
postMethod: async (requestDataArg) => {
const result = await this.postMethod(requestDataArg, targetConnection);
const result = await this.postMethod(requestDataArg, targetConnection as any);
return result;
},
}),
@@ -140,21 +287,125 @@ export class TypedSocket {
return typedrequest;
}
public async findTargetConnection(
findFuncArg: (connectionArg: plugins.smartsocket.SocketConnection) => boolean
) {
if (this.socketServerOrClient instanceof plugins.smartsocket.Smartsocket) {
for (const socketConnection of this.socketServerOrClient.socketConnections.getArray()) {
if (findFuncArg(socketConnection)) {
return socketConnection;
/**
* returns all matching target connections
* Works with both Smartsocket and SmartServe backends
* @param asyncFindFuncArg - async filter function
* @returns array of matching connections
*/
public async findAllTargetConnections(
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper) => Promise<boolean>
): Promise<(plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper)[]> {
// SmartServe mode
if (this.smartServeRef) {
const matchingConnections: ISmartServeConnectionWrapper[] = [];
for (const peer of this.smartServeRef.getWebSocketConnections()) {
let wrapper = this.smartServeConnectionWrappers.get(peer.id);
if (!wrapper) {
wrapper = wrapSmartServePeer(peer);
this.smartServeConnectionWrappers.set(peer.id, wrapper);
}
if (await asyncFindFuncArg(wrapper)) {
matchingConnections.push(wrapper);
}
}
} else {
console.warn('this method >>findTargetConnection<< is only available from the server');
return matchingConnections;
}
// Smartsocket mode
if (this.socketServerOrClient instanceof plugins.smartsocket.Smartsocket) {
const matchingSockets: plugins.smartsocket.SocketConnection[] = [];
for (const socketConnection of this.socketServerOrClient.socketConnections.getArray()) {
if (await asyncFindFuncArg(socketConnection)) {
matchingSockets.push(socketConnection);
}
}
return matchingSockets;
}
throw new Error('this method >>findTargetConnection<< is only available from the server');
}
/**
* returns a single target connection by returning the first one of all matching ones
* @param asyncFindFuncArg
* @returns
*/
public async findTargetConnection(
asyncFindFuncArg: (connectionArg: plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper) => Promise<boolean>
): Promise<plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper | undefined> {
const allMatching = await this.findAllTargetConnections(asyncFindFuncArg);
return allMatching[0];
}
/**
* Find all connections that have a specific tag
* Works with both Smartsocket and SmartServe backends
*/
public async findAllTargetConnectionsByTag<
TTag extends plugins.typedrequestInterfaces.ITag = any
>(keyArg: TTag['name'], payloadArg?: TTag['payload']): Promise<(plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper)[]> {
// SmartServe mode - use native filtering for better performance
if (this.smartServeRef) {
const peers = this.smartServeRef.getWebSocketConnectionsByTag(keyArg);
const results: ISmartServeConnectionWrapper[] = [];
for (const peer of peers) {
let wrapper = this.smartServeConnectionWrappers.get(peer.id);
if (!wrapper) {
wrapper = wrapSmartServePeer(peer);
this.smartServeConnectionWrappers.set(peer.id, wrapper);
}
// If payload specified, also filter by payload stored in peer.data
if (payloadArg !== undefined) {
const tag = await wrapper.getTagById(keyArg);
if (plugins.smartjson.stringify(tag?.payload) !== plugins.smartjson.stringify(payloadArg)) {
continue;
}
}
results.push(wrapper);
}
return results;
}
// Smartsocket mode - use existing logic
return this.findAllTargetConnections(async (socketConnectionArg) => {
let result: boolean;
if (!payloadArg) {
result = !!(await (socketConnectionArg as plugins.smartsocket.SocketConnection).getTagById(keyArg));
} else {
result = !!(
plugins.smartjson.stringify((await (socketConnectionArg as plugins.smartsocket.SocketConnection).getTagById(keyArg))?.payload) ===
plugins.smartjson.stringify(payloadArg)
);
}
return result;
});
}
/**
* Find a single connection by tag
*/
public async findTargetConnectionByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(
keyArg: TTag['name'],
payloadArg?: TTag['payload']
): Promise<plugins.smartsocket.SocketConnection | ISmartServeConnectionWrapper | undefined> {
const allResults = await this.findAllTargetConnectionsByTag(keyArg, payloadArg);
return allResults[0];
}
/**
* Stop the TypedSocket server/client
* Note: In SmartServe mode, SmartServe manages its own lifecycle
*/
public async stop() {
await this.socketServerOrClient.stop()
if (this.smartServeRef) {
// SmartServe manages its own lifecycle
// Clear our connection wrappers
this.smartServeConnectionWrappers.clear();
return;
}
await this.socketServerOrClient.stop();
}
}

View File

@@ -1,19 +1,18 @@
// @apiglobal scope
import * as typedrequest from '@apiglobal/typedrequest';
import * as typedrequestInterfaces from '@apiglobal/typedrequest-interfaces';
import * as typedrequest from '@api.global/typedrequest';
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
export {
typedrequest,
typedrequestInterfaces,
}
export { typedrequest, typedrequestInterfaces };
// @pushrocks scope
import * as isohash from '@pushrocks/isohash';
import * as smartsocket from '@pushrocks/smartsocket';
import * as smartstring from '@pushrocks/smartstring';
import * as isohash from '@push.rocks/isohash';
import * as smartjson from '@push.rocks/smartjson';
import * as smartrx from '@push.rocks/smartrx';
import * as smartsocket from '@push.rocks/smartsocket';
import * as smartstring from '@push.rocks/smartstring';
import * as smarturl from '@push.rocks/smarturl';
export {
isohash,
smartsocket,
smartstring
}
export { isohash, smartjson, smartrx, smartsocket, smartstring, smarturl };
// Optional SmartServe support (type-only imports for optional peer dependency)
export type { SmartServe, IWebSocketPeer } from '@push.rocks/smartserve';

14
tsconfig.json Normal file
View File

@@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}