Compare commits
122 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 56be583403 | |||
| 96745be056 | |||
| b2cfb58324 | |||
| 22ed5ebe59 | |||
| 1e53ee5b1a | |||
| 632045edd9 | |||
| cace6ca85a | |||
| 14966304e3 | |||
| e2e359c9c7 | |||
| acfd97c168 | |||
| 404f5ed3f3 | |||
| 001f18ad3b | |||
| 2e4adba867 | |||
| a6530e9752 | |||
| 7163c1dc67 | |||
| c2f4efd33d | |||
| bc7a828124 | |||
| f62497ce48 | |||
| 64e5f30bad | |||
| 1b41d5e3ad | |||
| c5954aa880 | |||
| b58d8084e9 | |||
| f765e60e1f | |||
| b726669c4b | |||
| 4f0066b5ca | |||
| 0edc903900 | |||
| fa41192377 | |||
| 725e3c65c6 | |||
| 4e9108f7df | |||
| 420d634e83 | |||
| eb596e5dd8 | |||
| 5748bd8280 | |||
| 4e8ea21df2 | |||
| 6f4be3baaa | |||
| a484060888 | |||
| c1b15daaca | |||
| f9397feaf0 | |||
| 889ec9c8ec | |||
| 5d460cf002 | |||
| 5e6ec0d311 | |||
| dd834590cc | |||
| 96b7354dae | |||
| 3a5533c4fe | |||
| 1f5f84763d | |||
| 6474112275 | |||
| a46c0cf395 | |||
| 8be5c352f4 | |||
| caaf947a46 | |||
| 2ec88494be | |||
| b80346d742 | |||
| aced21a968 | |||
| fa40e3a5dc | |||
| 9bb0008381 | |||
| 67bbea8811 | |||
| dc826cb65a | |||
| 1266a814c6 | |||
| 25a7397548 | |||
| 5009bec70c | |||
| d8d7b135f7 | |||
| 9738d88ec7 | |||
| 9d7f433685 | |||
| fc1124fb16 | |||
| 5e5f493dfa | |||
| 899a46f9de | |||
| 1412a06f4c | |||
| 51e6c5cf0e | |||
| 8d7eb3ff5f | |||
| a82f8ccc26 | |||
| d934f4b53b | |||
| 54b8a692ba | |||
| 2f39b5662d | |||
| 5b9e785159 | |||
| a5bca90eeb | |||
| 244016faed | |||
| 61719769a0 | |||
| 6e2855cf3c | |||
| 916052ef0b | |||
| 2f51e10fc4 | |||
| 6e2e2768e2 | |||
| 4c5abc89b8 | |||
| 5911d829f9 | |||
| eac735a691 | |||
| 4af7164a58 | |||
| 006073cbc8 | |||
| 7d8b41a5a6 | |||
| acca64fa31 | |||
| 1e570813a3 | |||
| 0199e8ef17 | |||
| 68def29c80 | |||
| 106eb12a7f | |||
| 5b868f1259 | |||
| 952835e46a | |||
| 5aa8048ce8 | |||
| 48112f97ce | |||
| 57a10080b5 | |||
| 7bdac2b89d | |||
| 6c49870dd6 | |||
| a2db05bfe3 | |||
| 69668731be | |||
| e586843d81 | |||
| fef1ae338a | |||
| 969b2d6686 | |||
| f4d820d37e | |||
| c08acd076e | |||
| c968de37d1 | |||
| 5b8f7514f4 | |||
| 53874a7772 | |||
| 479cf60239 | |||
| 825a264327 | |||
| 16305a4cf8 | |||
| e7176ebc79 | |||
| ad8ff504a9 | |||
| a23c5a0fba | |||
| 912b9bad51 | |||
| 6e4505256c | |||
| bd81f731ad | |||
| 50506f4cfa | |||
| 83450b8fd2 | |||
| 4a02ebea0c | |||
| ab2b068ac4 | |||
| f18be49423 | |||
| 09cd4c3feb |
137
.gitlab-ci.yml
137
.gitlab-ci.yml
@@ -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
24
.vscode/launch.json
vendored
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
88
changelog.md
Normal file
88
changelog.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-02-26 - 4.1.2 - fix(ci)
|
||||
update npmextra.json to rename keys, add release registries and add CI entry; remove legacy npmci configuration
|
||||
|
||||
- Renamed top-level key "gitzone" to "@git.zone/cli" and "tsdoc" to "@git.zone/tsdoc" to use scoped configuration keys.
|
||||
- Added release configuration under @git.zone/cli with registries [https://verdaccio.lossless.digital, https://registry.npmjs.org] and accessLevel set to public.
|
||||
- Removed legacy "npmci" block and introduced an "@ship.zone/szci" section (npmGlobalTools: []).
|
||||
- No source code changes; this is a configuration/CI/publishing metadata update. Current package.json version is 4.1.1, recommend a patch bump.
|
||||
|
||||
## 2026-02-26 - 4.1.1 - fix(typedsocket)
|
||||
reject pending requests on disconnect to avoid hanging promises
|
||||
|
||||
- Rejects all pending requests with Error('TypedSocket disconnected') when connection is lost
|
||||
- Clears pendingRequests map to prevent memory leaks
|
||||
- Preserves existing auto-reconnect scheduling behavior
|
||||
|
||||
## 2025-12-04 - 4.1.0 - feat(typedsocket)
|
||||
Add SmartServe integration, tagging and improved client reconnect/backoff; update deps and tests
|
||||
|
||||
- Add SmartServe integration: new TypedSocket.fromSmartServe(smartServe, typedRouter) with SmartServe connection wrappers and tag compatibility
|
||||
- Implement server-side tag handlers and storage (__typedsocket_setTag / __typedsocket_removeTag) with payloads stored under internal TAG_PREFIX
|
||||
- Add client improvements: TypedSocket.createClient(...) with autoReconnect, configurable exponential backoff (initialBackoffMs, maxBackoffMs, maxRetries) and connection status observable (statusSubject)
|
||||
- Expose client tag API: setTag(name, payload) and removeTag(name) to manage server-side tags
|
||||
- Server-side APIs for connection discovery: findAllTargetConnections, findTargetConnection, findAllTargetConnectionsByTag, findTargetConnectionByTag
|
||||
- Plugins and internal tooling updated: replace smartsocket exports with smartdelay and smartpromise; export smartpromise and smartdelay for internal use
|
||||
- Tests updated to use SmartServe for end-to-end scenarios (server/client message flow, tagging and connection discovery); test script changed to run in verbose mode
|
||||
- Bumped dependency versions and adjusted peer dependency for @push.rocks/smartserve to >=1.1.0
|
||||
|
||||
## 2025-12-03 - 4.0.0 - BREAKING CHANGE(TypedSocket.createServer)
|
||||
Remove SmartExpress attachment support from createServer and upgrade smartsocket to ^3.0.0
|
||||
|
||||
- Bump dependency @push.rocks/smartsocket from ^2.1.0 to ^3.0.0.
|
||||
- Remove optional SmartExpress attachment parameter from TypedSocket.createServer and remove the setExternalServer call — createServer now only accepts a TypedRouter and starts its own Smartsocket server.
|
||||
- Update README: remove the SmartExpress integration section and adjust the API docs to reflect the new createServer(router) signature.
|
||||
- Adjust TypeScript implementation to match the simplified createServer signature and behavior.
|
||||
|
||||
## 2025-12-02 - 3.1.1 - fix(package)
|
||||
Include pnpm packageManager metadata in package.json
|
||||
|
||||
- Added packageManager field to package.json: pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34
|
||||
- No runtime or API changes — metadata-only change
|
||||
|
||||
## 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 2022–2023.
|
||||
- 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 (2020–2022) included ongoing fixes and minor updates to stabilize the 1.x line.
|
||||
@@ -1,18 +1,35 @@
|
||||
{
|
||||
"gitzone": {
|
||||
"@git.zone/cli": {
|
||||
"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"
|
||||
]
|
||||
},
|
||||
"release": {
|
||||
"registries": [
|
||||
"https://verdaccio.lossless.digital",
|
||||
"https://registry.npmjs.org"
|
||||
],
|
||||
"accessLevel": "public"
|
||||
}
|
||||
},
|
||||
"npmci": {
|
||||
"npmGlobalTools": [],
|
||||
"npmAccessLevel": "public"
|
||||
"@git.zone/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"
|
||||
},
|
||||
"@ship.zone/szci": {
|
||||
"npmGlobalTools": []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
11393
package-lock.json
generated
11393
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
52
package.json
52
package.json
@@ -1,28 +1,41 @@
|
||||
{
|
||||
"name": "@apiglobal/typedsocket",
|
||||
"version": "1.0.2",
|
||||
"name": "@api.global/typedsocket",
|
||||
"version": "4.1.2",
|
||||
"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)"
|
||||
"test": "(tstest test/ --verbose)",
|
||||
"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.11.2",
|
||||
"tslint": "^6.1.3",
|
||||
"tslint-config-prettier": "^1.15.0"
|
||||
"@git.zone/tsbuild": "^3.1.2",
|
||||
"@git.zone/tsbundle": "^2.6.3",
|
||||
"@git.zone/tsrun": "^2.0.0",
|
||||
"@git.zone/tstest": "^3.1.3",
|
||||
"@push.rocks/smartenv": "^6.0.0",
|
||||
"@push.rocks/smartserve": "^1.1.2",
|
||||
"@push.rocks/tapbundle": "^6.0.3",
|
||||
"@types/node": "^24.10.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@apiglobal/typedrequest": "^1.0.55",
|
||||
"@pushrocks/smartsocket": "^1.1.68"
|
||||
"@api.global/typedrequest": "^3.1.11",
|
||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||
"@push.rocks/isohash": "^2.0.1",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartjson": "^5.2.0",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartrx": "^3.0.10",
|
||||
"@push.rocks/smartstring": "^4.1.0",
|
||||
"@push.rocks/smarturl": "^3.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@push.rocks/smartserve": ">=1.1.0"
|
||||
},
|
||||
"browserslist": [
|
||||
"last 1 chrome versions"
|
||||
@@ -38,5 +51,14 @@
|
||||
"cli.js",
|
||||
"npmextra.json",
|
||||
"readme.md"
|
||||
]
|
||||
],
|
||||
"keywords": [
|
||||
"WebSocket",
|
||||
"Type Safety",
|
||||
"Real-time Communication",
|
||||
"Client-Server Architecture",
|
||||
"TypeScript",
|
||||
"Networking"
|
||||
],
|
||||
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34"
|
||||
}
|
||||
|
||||
12326
pnpm-lock.yaml
generated
Normal file
12326
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
21
readme.hints.md
Normal file
21
readme.hints.md
Normal 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
|
||||
314
readme.md
314
readme.md
@@ -1,39 +1,297 @@
|
||||
# @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 | [](https://lossless.cloud)
|
||||
GitLab Pipline Test Coverage | [](https://lossless.cloud)
|
||||
npm | [](https://lossless.cloud)
|
||||
Snyk | [](https://lossless.cloud)
|
||||
TypeScript Support | [](https://lossless.cloud)
|
||||
node Support | [](https://nodejs.org/dist/latest-v10.x/docs/api/)
|
||||
Code Style | [](https://lossless.cloud)
|
||||
PackagePhobia (total standalone install weight) | [](https://lossless.cloud)
|
||||
PackagePhobia (package size on registry) | [](https://lossless.cloud)
|
||||
BundlePhobia (total size when bundled) | [](https://lossless.cloud)
|
||||
Platform support | [](https://lossless.cloud) [](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
|
||||
- 🚀 **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
|
||||
|
||||
## Contribution
|
||||
- TypeScript project setup
|
||||
- Basic understanding of async/await patterns
|
||||
- Familiarity with `@api.global/typedrequest` concepts
|
||||
|
||||
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). :)
|
||||
### Define Your Request Interface
|
||||
|
||||
For further information read the linked docs at the top of this readme.
|
||||
First, define the typed request interface that both client and server will use:
|
||||
|
||||
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
|
||||
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
|
||||
```typescript
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
[](https://maintainedby.lossless.com)
|
||||
interface IGreetingRequest extends typedrequestInterfaces.implementsTR<
|
||||
typedrequestInterfaces.ITypedRequest,
|
||||
IGreetingRequest
|
||||
> {
|
||||
method: 'greet';
|
||||
request: {
|
||||
name: string;
|
||||
};
|
||||
response: {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
### Server Setup
|
||||
|
||||
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 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)` | Creates a WebSocket server (defaults to port 3000). |
|
||||
| `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.
|
||||
|
||||
9
test-inactive/test.browser.ts
Normal file
9
test-inactive/test.browser.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { tap, expect } from '@push.rocks/tapbundle';
|
||||
|
||||
import * as typedsocket from '../ts/index.js';
|
||||
|
||||
tap.test('should create a client', async () => {
|
||||
console.log('Browser test') // TODO: implement browser tests
|
||||
});
|
||||
|
||||
tap.start();
|
||||
122
test/test.ts
122
test/test.ts
@@ -1,10 +1,120 @@
|
||||
import { expect, tap } from '@pushrocks/tapbundle';
|
||||
import * as typedsocket from '../ts/index';
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
import { SmartServe } from '@push.rocks/smartserve';
|
||||
|
||||
let testTypedSocket: typedsocket.TypedSocket;
|
||||
import * as typedsocket from '../ts/index.js';
|
||||
|
||||
tap.test('first test', async () => {
|
||||
testTypedSocket = new typedsocket.TypedSocket();
|
||||
interface IRequest_Client_Server
|
||||
extends typedrequestInterfaces.implementsTR<
|
||||
typedrequestInterfaces.ITypedRequest,
|
||||
IRequest_Client_Server
|
||||
> {
|
||||
method: 'sayhi';
|
||||
request: {
|
||||
greeting: string;
|
||||
};
|
||||
response: {
|
||||
answer: string;
|
||||
};
|
||||
}
|
||||
|
||||
let testSmartServe: SmartServe;
|
||||
let testTypedSocketServer: typedsocket.TypedSocket;
|
||||
let testTypedSocketClient: typedsocket.TypedSocket;
|
||||
|
||||
const testTypedRouter = new typedrequest.TypedRouter();
|
||||
const clientTypedRouter = new typedrequest.TypedRouter();
|
||||
|
||||
tap.test('should add some handlers', async () => {
|
||||
// Server-side handler
|
||||
testTypedRouter.addTypedHandler<IRequest_Client_Server>(
|
||||
new typedrequest.TypedHandler('sayhi', async (requestData) => {
|
||||
return {
|
||||
answer: `ok, got it : ${requestData.greeting}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Client-side handler (for server-to-client messages)
|
||||
clientTypedRouter.addTypedHandler<IRequest_Client_Server>(
|
||||
new typedrequest.TypedHandler('sayhi', async (requestData) => {
|
||||
return {
|
||||
answer: `client got: ${requestData.greeting}`,
|
||||
};
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
tap.start();
|
||||
tap.test('should create Server and Client', async (tools) => {
|
||||
// Create SmartServe with TypedRouter for WebSocket
|
||||
testSmartServe = new SmartServe({
|
||||
port: 3000,
|
||||
websocket: {
|
||||
typedRouter: testTypedRouter,
|
||||
},
|
||||
});
|
||||
await testSmartServe.start();
|
||||
console.log('SmartServe started on port 3000');
|
||||
|
||||
// Create TypedSocket server from SmartServe
|
||||
testTypedSocketServer = typedsocket.TypedSocket.fromSmartServe(testSmartServe, testTypedRouter);
|
||||
console.log('TypedSocket server created');
|
||||
|
||||
// Create client
|
||||
testTypedSocketClient = await typedsocket.TypedSocket.createClient(
|
||||
clientTypedRouter,
|
||||
'http://localhost:3000'
|
||||
);
|
||||
console.log('TypedSocket client connected');
|
||||
|
||||
console.log('test: waiting 1 second for connection to stabilize');
|
||||
await tools.delayFor(1000);
|
||||
});
|
||||
|
||||
tap.test('should set tags via TypedRequest', async () => {
|
||||
console.log('Setting tag...');
|
||||
await testTypedSocketClient.setTag('testTag', { userId: 123 });
|
||||
console.log('Tag set successfully');
|
||||
});
|
||||
|
||||
tap.test('should process messages from client to server', async () => {
|
||||
console.log('Testing client to server...');
|
||||
const myClientSideTypedRequest =
|
||||
testTypedSocketClient.createTypedRequest<IRequest_Client_Server>('sayhi');
|
||||
const response = await myClientSideTypedRequest.fire({
|
||||
greeting: 'that is a greeting from the client',
|
||||
});
|
||||
console.log('Client got response:', response);
|
||||
expect(response.answer).toContain('ok, got it');
|
||||
});
|
||||
|
||||
tap.test('should find connections by tag', async () => {
|
||||
console.log('Finding connections by tag...');
|
||||
const connections = await testTypedSocketServer.findAllTargetConnectionsByTag('testTag');
|
||||
console.log(`Found ${connections.length} connections with tag`);
|
||||
expect(connections.length).toEqual(1);
|
||||
});
|
||||
|
||||
tap.test('should process messages from server to client', async () => {
|
||||
console.log('Testing server to client...');
|
||||
const connections = await testTypedSocketServer.findAllTargetConnectionsByTag('testTag');
|
||||
const myServerSideTypedRequest =
|
||||
testTypedSocketServer.createTypedRequest<IRequest_Client_Server>('sayhi', connections[0]);
|
||||
const response = await myServerSideTypedRequest.fire({
|
||||
greeting: 'that is a greeting from the server',
|
||||
});
|
||||
console.log('Server got response:', response);
|
||||
expect(response.answer).toContain('client got');
|
||||
});
|
||||
|
||||
tap.test('should disconnect', async (tools) => {
|
||||
console.log('Stopping client...');
|
||||
await testTypedSocketClient.stop();
|
||||
console.log('Stopping server...');
|
||||
await testSmartServe.stop();
|
||||
console.log('All stopped');
|
||||
tools.delayFor(500).then(() => process.exit(0));
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
|
||||
8
ts/00_commitinfo_data.ts
Normal file
8
ts/00_commitinfo_data.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* autocreated commitinfo by @push.rocks/commitinfo
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@api.global/typedsocket',
|
||||
version: '4.1.2',
|
||||
description: 'A library for creating typed WebSocket connections, supporting bi-directional communication with type safety.'
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
export * from './typedsocket.classes.typedsocket';
|
||||
export * from './typedsocket.classes.typedsocket.js';
|
||||
@@ -1,9 +1,619 @@
|
||||
import * as plugins from './typedsocket.plugins';
|
||||
import * as plugins from './typedsocket.plugins.js';
|
||||
|
||||
export type TTypedSocketSide = 'server' | 'client';
|
||||
export type TConnectionStatus = 'new' | 'connecting' | 'connected' | 'disconnected' | 'reconnecting';
|
||||
|
||||
const TAG_PREFIX = '__typedsocket_tag__';
|
||||
|
||||
/**
|
||||
* Internal TypedRequest interfaces for tag management
|
||||
*/
|
||||
interface IReq_SetClientTag extends plugins.typedrequestInterfaces.ITypedRequest {
|
||||
method: '__typedsocket_setTag';
|
||||
request: { name: string; payload: any };
|
||||
response: { success: boolean };
|
||||
}
|
||||
|
||||
interface IReq_RemoveClientTag extends plugins.typedrequestInterfaces.ITypedRequest {
|
||||
method: '__typedsocket_removeTag';
|
||||
request: { name: string };
|
||||
response: { success: boolean };
|
||||
}
|
||||
|
||||
/**
|
||||
* Options for creating a TypedSocket client
|
||||
*/
|
||||
export interface ITypedSocketClientOptions {
|
||||
autoReconnect?: boolean;
|
||||
maxRetries?: number;
|
||||
initialBackoffMs?: number;
|
||||
maxBackoffMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper for SmartServe's IWebSocketPeer to provide tag compatibility
|
||||
*/
|
||||
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 {
|
||||
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 {
|
||||
public static async createServer () {}
|
||||
// ============================================================================
|
||||
// STATIC METHODS
|
||||
// ============================================================================
|
||||
|
||||
public static createCleint() {}
|
||||
/**
|
||||
* Creates a TypedSocket client using native WebSocket.
|
||||
* Works in both browser and Node.js environments.
|
||||
*
|
||||
* @param typedrouterArg - TypedRouter for handling server-initiated requests
|
||||
* @param serverUrlArg - Server URL (e.g., 'http://localhost:3000' or 'wss://example.com')
|
||||
* @param options - Connection options
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const typedRouter = new TypedRouter();
|
||||
* const client = await TypedSocket.createClient(
|
||||
* typedRouter,
|
||||
* 'http://localhost:3000',
|
||||
* { autoReconnect: true }
|
||||
* );
|
||||
* ```
|
||||
*/
|
||||
public static async createClient(
|
||||
typedrouterArg: plugins.typedrequest.TypedRouter,
|
||||
serverUrlArg: string,
|
||||
options: ITypedSocketClientOptions = {}
|
||||
): Promise<TypedSocket> {
|
||||
const defaultOptions: Required<ITypedSocketClientOptions> = {
|
||||
autoReconnect: true,
|
||||
maxRetries: 100,
|
||||
initialBackoffMs: 1000,
|
||||
maxBackoffMs: 60000,
|
||||
};
|
||||
const opts = { ...defaultOptions, ...options };
|
||||
|
||||
constructor() {}
|
||||
}
|
||||
const typedSocket = new TypedSocket('client', typedrouterArg);
|
||||
typedSocket.clientOptions = opts;
|
||||
typedSocket.serverUrl = serverUrlArg;
|
||||
typedSocket.currentBackoff = opts.initialBackoffMs;
|
||||
|
||||
await typedSocket.connect();
|
||||
|
||||
return typedSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current window location origin URL.
|
||||
* Useful in browser environments for connecting to the same origin.
|
||||
*/
|
||||
public static useWindowLocationOriginUrl = (): string => {
|
||||
return plugins.smarturl.Smarturl.createFromUrl(globalThis.location.origin).toString();
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a TypedSocket server from an existing SmartServe instance.
|
||||
* This is the only way to create a server-side TypedSocket.
|
||||
*
|
||||
* @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>();
|
||||
|
||||
// Register built-in tag handlers
|
||||
TypedSocket.registerTagHandlers(typedRouterArg);
|
||||
|
||||
const typedSocket = new TypedSocket('server', typedRouterArg);
|
||||
typedSocket.smartServeRef = smartServeArg;
|
||||
typedSocket.smartServeConnectionWrappers = connectionWrappers;
|
||||
|
||||
return typedSocket;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers built-in TypedHandlers for tag management
|
||||
*/
|
||||
private static registerTagHandlers(typedRouter: plugins.typedrequest.TypedRouter): void {
|
||||
// Set tag handler
|
||||
typedRouter.addTypedHandler<IReq_SetClientTag>(
|
||||
new plugins.typedrequest.TypedHandler('__typedsocket_setTag', async (data, meta) => {
|
||||
const peer = meta?.localData?.peer as plugins.IWebSocketPeer;
|
||||
if (!peer) {
|
||||
console.warn('setTag: No peer found in request context');
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
peer.tags.add(data.name);
|
||||
peer.data.set(`${TAG_PREFIX}${data.name}`, data.payload);
|
||||
|
||||
return { success: true };
|
||||
})
|
||||
);
|
||||
|
||||
// Remove tag handler
|
||||
typedRouter.addTypedHandler<IReq_RemoveClientTag>(
|
||||
new plugins.typedrequest.TypedHandler('__typedsocket_removeTag', async (data, meta) => {
|
||||
const peer = meta?.localData?.peer as plugins.IWebSocketPeer;
|
||||
if (!peer) {
|
||||
console.warn('removeTag: No peer found in request context');
|
||||
return { success: false };
|
||||
}
|
||||
|
||||
peer.tags.delete(data.name);
|
||||
peer.data.delete(`${TAG_PREFIX}${data.name}`);
|
||||
|
||||
return { success: true };
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// INSTANCE PROPERTIES
|
||||
// ============================================================================
|
||||
|
||||
public readonly side: TTypedSocketSide;
|
||||
public readonly typedrouter: plugins.typedrequest.TypedRouter;
|
||||
|
||||
// Connection status observable
|
||||
public statusSubject = new plugins.smartrx.rxjs.Subject<TConnectionStatus>();
|
||||
private connectionStatus: TConnectionStatus = 'new';
|
||||
|
||||
// Client-specific properties
|
||||
private websocket: WebSocket | null = null;
|
||||
private clientOptions: Required<ITypedSocketClientOptions> | null = null;
|
||||
private serverUrl: string = '';
|
||||
private retryCount = 0;
|
||||
private currentBackoff = 1000;
|
||||
private pendingRequests = new Map<string, {
|
||||
resolve: (response: any) => void;
|
||||
reject: (error: Error) => void;
|
||||
}>();
|
||||
|
||||
// Server-specific properties (SmartServe mode)
|
||||
private smartServeRef: plugins.SmartServe | null = null;
|
||||
private smartServeConnectionWrappers = new Map<string, ISmartServeConnectionWrapper>();
|
||||
|
||||
// ============================================================================
|
||||
// CONSTRUCTOR
|
||||
// ============================================================================
|
||||
|
||||
private constructor(
|
||||
sideArg: TTypedSocketSide,
|
||||
typedrouterArg: plugins.typedrequest.TypedRouter
|
||||
) {
|
||||
this.side = sideArg;
|
||||
this.typedrouter = typedrouterArg;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CLIENT METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Connects the client to the server using native WebSocket
|
||||
*/
|
||||
private async connect(): Promise<void> {
|
||||
const done = plugins.smartpromise.defer<void>();
|
||||
|
||||
this.updateStatus('connecting');
|
||||
|
||||
// Convert HTTP URL to WebSocket URL
|
||||
const wsUrl = this.toWebSocketUrl(this.serverUrl);
|
||||
console.log(`TypedSocket connecting to ${wsUrl}...`);
|
||||
|
||||
this.websocket = new WebSocket(wsUrl);
|
||||
|
||||
const connectionTimeout = setTimeout(() => {
|
||||
if (this.connectionStatus !== 'connected') {
|
||||
console.warn('TypedSocket connection timeout');
|
||||
this.websocket?.close();
|
||||
done.reject(new Error('Connection timeout'));
|
||||
}
|
||||
}, 10000);
|
||||
|
||||
this.websocket.onopen = () => {
|
||||
clearTimeout(connectionTimeout);
|
||||
console.log('TypedSocket connected!');
|
||||
this.updateStatus('connected');
|
||||
this.retryCount = 0;
|
||||
this.currentBackoff = this.clientOptions?.initialBackoffMs ?? 1000;
|
||||
done.resolve();
|
||||
};
|
||||
|
||||
this.websocket.onmessage = async (event) => {
|
||||
await this.handleMessage(event.data);
|
||||
};
|
||||
|
||||
this.websocket.onclose = () => {
|
||||
clearTimeout(connectionTimeout);
|
||||
this.handleDisconnect();
|
||||
};
|
||||
|
||||
this.websocket.onerror = (error) => {
|
||||
console.error('TypedSocket WebSocket error:', error);
|
||||
};
|
||||
|
||||
try {
|
||||
await done.promise;
|
||||
} catch (err) {
|
||||
clearTimeout(connectionTimeout);
|
||||
if (this.clientOptions?.autoReconnect) {
|
||||
await this.scheduleReconnect();
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an HTTP(S) URL to a WebSocket URL
|
||||
*/
|
||||
private toWebSocketUrl(url: string): string {
|
||||
const parsed = new URL(url);
|
||||
const wsProtocol = parsed.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
return `${wsProtocol}//${parsed.host}${parsed.pathname}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles incoming WebSocket messages
|
||||
*/
|
||||
private async handleMessage(data: string | ArrayBuffer): Promise<void> {
|
||||
try {
|
||||
const messageText = typeof data === 'string' ? data : new TextDecoder().decode(data);
|
||||
const message = plugins.smartjson.parse(messageText) as plugins.typedrequestInterfaces.ITypedRequest;
|
||||
|
||||
// Check if this is a response to a pending request
|
||||
if (message.correlation?.id && this.pendingRequests.has(message.correlation.id)) {
|
||||
const pending = this.pendingRequests.get(message.correlation.id)!;
|
||||
this.pendingRequests.delete(message.correlation.id);
|
||||
pending.resolve(message);
|
||||
return;
|
||||
}
|
||||
|
||||
// Server-initiated request - route through TypedRouter
|
||||
const response = await this.typedrouter.routeAndAddResponse(message);
|
||||
if (response && this.websocket?.readyState === WebSocket.OPEN) {
|
||||
this.websocket.send(plugins.smartjson.stringify(response));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('TypedSocket failed to process message:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles WebSocket disconnection
|
||||
*/
|
||||
private handleDisconnect(): void {
|
||||
if (this.connectionStatus === 'disconnected') {
|
||||
return; // Already handled
|
||||
}
|
||||
|
||||
this.updateStatus('disconnected');
|
||||
|
||||
// Reject all pending requests — the connection is gone and they'll never receive a response
|
||||
for (const [id, pending] of this.pendingRequests) {
|
||||
pending.reject(new Error('TypedSocket disconnected'));
|
||||
}
|
||||
this.pendingRequests.clear();
|
||||
|
||||
if (this.clientOptions?.autoReconnect && this.retryCount < this.clientOptions.maxRetries) {
|
||||
this.scheduleReconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a reconnection attempt with exponential backoff
|
||||
*/
|
||||
private async scheduleReconnect(): Promise<void> {
|
||||
if (!this.clientOptions) return;
|
||||
|
||||
this.updateStatus('reconnecting');
|
||||
this.retryCount++;
|
||||
|
||||
// Exponential backoff with jitter
|
||||
const jitter = this.currentBackoff * 0.2 * (Math.random() * 2 - 1);
|
||||
const delay = Math.min(this.currentBackoff + jitter, this.clientOptions.maxBackoffMs);
|
||||
|
||||
console.log(`TypedSocket reconnecting in ${Math.round(delay)}ms (attempt ${this.retryCount}/${this.clientOptions.maxRetries})`);
|
||||
|
||||
await plugins.smartdelay.delayFor(delay);
|
||||
|
||||
// Increase backoff for next time
|
||||
this.currentBackoff = Math.min(this.currentBackoff * 2, this.clientOptions.maxBackoffMs);
|
||||
|
||||
try {
|
||||
await this.connect();
|
||||
} catch (err) {
|
||||
console.error('TypedSocket reconnection failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates connection status and notifies subscribers
|
||||
*/
|
||||
private updateStatus(status: TConnectionStatus): void {
|
||||
if (this.connectionStatus !== status) {
|
||||
this.connectionStatus = status;
|
||||
this.statusSubject.next(status);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request to the server and waits for response (client-side)
|
||||
*/
|
||||
private async sendRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(
|
||||
request: T
|
||||
): Promise<T> {
|
||||
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) {
|
||||
throw new Error('WebSocket not connected');
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pendingRequests.delete(request.correlation.id);
|
||||
reject(new Error('Request timeout'));
|
||||
}, 30000);
|
||||
|
||||
this.pendingRequests.set(request.correlation.id, {
|
||||
resolve: (response) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(response);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
|
||||
this.websocket!.send(plugins.smartjson.stringify(request));
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// PUBLIC API - SHARED
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Creates a TypedRequest for the specified method.
|
||||
* On clients, sends to the server.
|
||||
* On servers, sends to the specified target connection.
|
||||
*/
|
||||
public createTypedRequest<T extends plugins.typedrequestInterfaces.ITypedRequest>(
|
||||
methodName: T['method'],
|
||||
targetConnection?: ISmartServeConnectionWrapper
|
||||
): plugins.typedrequest.TypedRequest<T> {
|
||||
const postMethod = async (requestDataArg: T): Promise<T> => {
|
||||
if (this.side === 'client') {
|
||||
return this.sendRequest(requestDataArg);
|
||||
}
|
||||
|
||||
// Server-side: send to target connection
|
||||
if (!this.smartServeRef) {
|
||||
throw new Error('Server not initialized');
|
||||
}
|
||||
|
||||
let target = targetConnection;
|
||||
if (!target) {
|
||||
const allConnections = this.smartServeRef.getWebSocketConnections();
|
||||
if (allConnections.length === 1) {
|
||||
const peer = allConnections[0];
|
||||
target = this.getOrCreateWrapper(peer);
|
||||
} else if (allConnections.length === 0) {
|
||||
throw new Error('No WebSocket connections available');
|
||||
} else {
|
||||
throw new Error('Multiple connections available - specify targetConnection');
|
||||
}
|
||||
}
|
||||
|
||||
// Register interest for response
|
||||
const interest = await this.typedrouter.fireEventInterestMap.addInterest(
|
||||
requestDataArg.correlation.id,
|
||||
requestDataArg
|
||||
);
|
||||
|
||||
// Send request
|
||||
target.peer.send(plugins.smartjson.stringify(requestDataArg));
|
||||
|
||||
// Wait for response
|
||||
return await interest.interestFullfilled as T;
|
||||
};
|
||||
|
||||
return new plugins.typedrequest.TypedRequest<T>(
|
||||
new plugins.typedrequest.TypedTarget({ postMethod }),
|
||||
methodName
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current connection status
|
||||
*/
|
||||
public getStatus(): TConnectionStatus {
|
||||
return this.connectionStatus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the TypedSocket client or cleans up server state
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
if (this.side === 'client') {
|
||||
if (this.clientOptions) {
|
||||
this.clientOptions.autoReconnect = false;
|
||||
}
|
||||
if (this.websocket) {
|
||||
this.websocket.close();
|
||||
this.websocket = null;
|
||||
}
|
||||
this.pendingRequests.clear();
|
||||
} else {
|
||||
// Server mode - just clear wrappers (SmartServe manages its own lifecycle)
|
||||
this.smartServeConnectionWrappers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// CLIENT-ONLY METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Sets a tag on this client connection.
|
||||
* Tags are stored on the server and can be used for filtering.
|
||||
* @client-only
|
||||
*/
|
||||
public async setTag<T extends plugins.typedrequestInterfaces.ITag>(
|
||||
name: T['name'],
|
||||
payload: T['payload']
|
||||
): Promise<void> {
|
||||
if (this.side !== 'client') {
|
||||
throw new Error('setTag is only available on clients');
|
||||
}
|
||||
|
||||
const request = this.createTypedRequest<IReq_SetClientTag>('__typedsocket_setTag');
|
||||
const response = await request.fire({ name, payload });
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error('Failed to set tag on server');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a tag from this client connection.
|
||||
* @client-only
|
||||
*/
|
||||
public async removeTag(name: string): Promise<void> {
|
||||
if (this.side !== 'client') {
|
||||
throw new Error('removeTag is only available on clients');
|
||||
}
|
||||
|
||||
const request = this.createTypedRequest<IReq_RemoveClientTag>('__typedsocket_removeTag');
|
||||
const response = await request.fire({ name });
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error('Failed to remove tag on server');
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SERVER-ONLY METHODS
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Gets or creates a connection wrapper for a peer
|
||||
*/
|
||||
private getOrCreateWrapper(peer: plugins.IWebSocketPeer): ISmartServeConnectionWrapper {
|
||||
let wrapper = this.smartServeConnectionWrappers.get(peer.id);
|
||||
if (!wrapper) {
|
||||
wrapper = wrapSmartServePeer(peer);
|
||||
this.smartServeConnectionWrappers.set(peer.id, wrapper);
|
||||
}
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all connections matching the filter function.
|
||||
* @server-only
|
||||
*/
|
||||
public async findAllTargetConnections(
|
||||
asyncFindFuncArg: (connectionArg: ISmartServeConnectionWrapper) => Promise<boolean>
|
||||
): Promise<ISmartServeConnectionWrapper[]> {
|
||||
if (this.side !== 'server' || !this.smartServeRef) {
|
||||
throw new Error('findAllTargetConnections is only available on servers');
|
||||
}
|
||||
|
||||
const matchingConnections: ISmartServeConnectionWrapper[] = [];
|
||||
for (const peer of this.smartServeRef.getWebSocketConnections()) {
|
||||
const wrapper = this.getOrCreateWrapper(peer);
|
||||
if (await asyncFindFuncArg(wrapper)) {
|
||||
matchingConnections.push(wrapper);
|
||||
}
|
||||
}
|
||||
return matchingConnections;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first connection matching the filter function.
|
||||
* @server-only
|
||||
*/
|
||||
public async findTargetConnection(
|
||||
asyncFindFuncArg: (connectionArg: ISmartServeConnectionWrapper) => Promise<boolean>
|
||||
): Promise<ISmartServeConnectionWrapper | undefined> {
|
||||
const allMatching = await this.findAllTargetConnections(asyncFindFuncArg);
|
||||
return allMatching[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all connections with the specified tag.
|
||||
* @server-only
|
||||
*/
|
||||
public async findAllTargetConnectionsByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(
|
||||
keyArg: TTag['name'],
|
||||
payloadArg?: TTag['payload']
|
||||
): Promise<ISmartServeConnectionWrapper[]> {
|
||||
if (this.side !== 'server' || !this.smartServeRef) {
|
||||
throw new Error('findAllTargetConnectionsByTag is only available on servers');
|
||||
}
|
||||
|
||||
const peers = this.smartServeRef.getWebSocketConnectionsByTag(keyArg);
|
||||
const results: ISmartServeConnectionWrapper[] = [];
|
||||
|
||||
for (const peer of peers) {
|
||||
const wrapper = this.getOrCreateWrapper(peer);
|
||||
|
||||
// If payload specified, also filter by payload
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first connection with the specified tag.
|
||||
* @server-only
|
||||
*/
|
||||
public async findTargetConnectionByTag<TTag extends plugins.typedrequestInterfaces.ITag = any>(
|
||||
keyArg: TTag['name'],
|
||||
payloadArg?: TTag['payload']
|
||||
): Promise<ISmartServeConnectionWrapper | undefined> {
|
||||
const allResults = await this.findAllTargetConnectionsByTag(keyArg, payloadArg);
|
||||
return allResults[0];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
// @apiglobal scope
|
||||
import * as typedrequest from '@apiglobal/typedrequest';
|
||||
import * as typedrequest from '@api.global/typedrequest';
|
||||
import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces';
|
||||
|
||||
export {
|
||||
typedrequest
|
||||
}
|
||||
export { typedrequest, typedrequestInterfaces };
|
||||
|
||||
// @pushrocks scope
|
||||
import * as smartsocket from '@pushrocks/smartsocket';
|
||||
import * as isohash from '@push.rocks/isohash';
|
||||
import * as smartdelay from '@push.rocks/smartdelay';
|
||||
import * as smartjson from '@push.rocks/smartjson';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
import * as smartrx from '@push.rocks/smartrx';
|
||||
import * as smartstring from '@push.rocks/smartstring';
|
||||
import * as smarturl from '@push.rocks/smarturl';
|
||||
|
||||
export {
|
||||
smartsocket
|
||||
}
|
||||
export { isohash, smartdelay, smartjson, smartpromise, smartrx, smartstring, smarturl };
|
||||
|
||||
// SmartServe - required for server-side WebSocket support
|
||||
export type { SmartServe, IWebSocketPeer } from '@push.rocks/smartserve';
|
||||
|
||||
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"verbatimModuleSyntax": true
|
||||
},
|
||||
"exclude": [
|
||||
"dist_*/**/*.d.ts"
|
||||
]
|
||||
}
|
||||
17
tslint.json
17
tslint.json
@@ -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"
|
||||
}
|
||||
Reference in New Issue
Block a user