itty-sockets 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/FUNDING.yml +12 -0
- package/.github/workflows/coverage.yml +19 -0
- package/.github/workflows/lint.yml +18 -0
- package/.github/workflows/release.yml +29 -0
- package/.github/workflows/verify.yml +18 -0
- package/.prettierrc +7 -0
- package/CHANGELOG.md +15 -0
- package/CODE_OF_CONDUCT.md +128 -0
- package/CONTRIBUTING.md +92 -0
- package/LICENSE +21 -0
- package/README.md +117 -0
- package/bun.lockb +0 -0
- package/bunfig.toml +3 -0
- package/eslint.config.mjs +43 -0
- package/package.json +66 -0
- package/rollup.config.mjs +82 -0
- package/scripts/inject-snippet.mjs +19 -0
- package/src/connect.spec.ts +211 -0
- package/src/connect.ts +99 -0
- package/src/index.ts +2 -0
- package/src/ws.spec.ts +149 -0
- package/src/ws.ts +89 -0
- package/test.ts +0 -0
- package/tsconfig.json +27 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# These are supported funding model platforms
|
|
2
|
+
|
|
3
|
+
github: kwhitley
|
|
4
|
+
open_collective: kevinrwhitley
|
|
5
|
+
# patreon: # Replace with a single Patreon username
|
|
6
|
+
# ko_fi: # Replace with a single Ko-fi username
|
|
7
|
+
# tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
|
8
|
+
# community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
|
9
|
+
# liberapay: # Replace with a single Liberapay username
|
|
10
|
+
# issuehunt: # Replace with a single IssueHunt username
|
|
11
|
+
# otechie: # Replace with a single Otechie username
|
|
12
|
+
# custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
on: ['push', 'pull_request_target']
|
|
2
|
+
|
|
3
|
+
name: Test Coveralls
|
|
4
|
+
|
|
5
|
+
jobs:
|
|
6
|
+
build:
|
|
7
|
+
name: Build
|
|
8
|
+
runs-on: ubuntu-latest
|
|
9
|
+
steps:
|
|
10
|
+
- uses: actions/checkout@v1
|
|
11
|
+
- uses: oven-sh/setup-bun@v2.0.1
|
|
12
|
+
- name: install, make test-coverage
|
|
13
|
+
run: |
|
|
14
|
+
bun install
|
|
15
|
+
bun test --coverage
|
|
16
|
+
- name: Coveralls
|
|
17
|
+
uses: coverallsapp/github-action@master
|
|
18
|
+
with:
|
|
19
|
+
github-token: ${{ secrets.GITHUB_TOKEN }}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
name: lint
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [v1.x]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [v1.x]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v2
|
|
15
|
+
- uses: oven-sh/setup-bun@v2.0.1
|
|
16
|
+
- name: Install dependencies
|
|
17
|
+
- run: bun install
|
|
18
|
+
- run: bun run lint
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
name: Create Release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- '*'
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
steps:
|
|
12
|
+
- name: Check out code
|
|
13
|
+
uses: actions/checkout@v2
|
|
14
|
+
|
|
15
|
+
- name: Prepare tag for release notes
|
|
16
|
+
id: prep
|
|
17
|
+
run: echo "::set-output name=tag::$(echo ${GITHUB_REF#refs/tags/} | sed 's/\.//g')"
|
|
18
|
+
|
|
19
|
+
- name: Create Release
|
|
20
|
+
uses: actions/create-release@v1
|
|
21
|
+
env:
|
|
22
|
+
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
23
|
+
with:
|
|
24
|
+
tag_name: ${{ github.ref }}
|
|
25
|
+
release_name: Release ${{ github.ref }}
|
|
26
|
+
body: |
|
|
27
|
+
See [${{ github.ref_name }} CHANGELOG entry](https://github.com/kwhitley/itty-chroma/blob/v0.x/CHANGELOG.md#${{ steps.prep.outputs.tag }}) for notes
|
|
28
|
+
draft: false
|
|
29
|
+
prerelease: false
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
name: build
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [v0.x]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [v0.x]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
build:
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v2
|
|
15
|
+
- uses: oven-sh/setup-bun@v2.0.1
|
|
16
|
+
- name: Install dependencies
|
|
17
|
+
- run: bun install
|
|
18
|
+
- run: bun run verify
|
package/.prettierrc
ADDED
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
## Changelog
|
|
2
|
+
|
|
3
|
+
#### v1.0.0
|
|
4
|
+
- initial public release, considered stable
|
|
5
|
+
#### v0.1.18
|
|
6
|
+
- final pre-release
|
|
7
|
+
#### v0.1.17
|
|
8
|
+
- semifinal README
|
|
9
|
+
#### v0.1.16
|
|
10
|
+
- updates to README
|
|
11
|
+
#### v0.1.15
|
|
12
|
+
- mic check... check, check
|
|
13
|
+
#### v0.1.x
|
|
14
|
+
- test release
|
|
15
|
+
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
|
2
|
+
|
|
3
|
+
## Our Pledge
|
|
4
|
+
|
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
|
9
|
+
nationality, personal appearance, race, religion, or sexual identity
|
|
10
|
+
and orientation.
|
|
11
|
+
|
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
13
|
+
diverse, inclusive, and healthy community.
|
|
14
|
+
|
|
15
|
+
## Our Standards
|
|
16
|
+
|
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
|
18
|
+
community include:
|
|
19
|
+
|
|
20
|
+
- Demonstrating empathy and kindness toward other people
|
|
21
|
+
- Being respectful of differing opinions, viewpoints, and experiences
|
|
22
|
+
- Giving and gracefully accepting constructive feedback
|
|
23
|
+
- Accepting responsibility and apologizing to those affected by our mistakes,
|
|
24
|
+
and learning from the experience
|
|
25
|
+
- Focusing on what is best not just for us as individuals, but for the
|
|
26
|
+
overall community
|
|
27
|
+
|
|
28
|
+
Examples of unacceptable behavior include:
|
|
29
|
+
|
|
30
|
+
- The use of sexualized language or imagery, and sexual attention or
|
|
31
|
+
advances of any kind
|
|
32
|
+
- Trolling, insulting or derogatory comments, and personal or political attacks
|
|
33
|
+
- Public or private harassment
|
|
34
|
+
- Publishing others' private information, such as a physical or email
|
|
35
|
+
address, without their explicit permission
|
|
36
|
+
- Other conduct which could reasonably be considered inappropriate in a
|
|
37
|
+
professional setting
|
|
38
|
+
|
|
39
|
+
## Enforcement Responsibilities
|
|
40
|
+
|
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
44
|
+
or harmful.
|
|
45
|
+
|
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
49
|
+
decisions when appropriate.
|
|
50
|
+
|
|
51
|
+
## Scope
|
|
52
|
+
|
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
|
54
|
+
an individual is officially representing the community in public spaces.
|
|
55
|
+
Examples of representing our community include using an official e-mail address,
|
|
56
|
+
posting via an official social media account, or acting as an appointed
|
|
57
|
+
representative at an online or offline event.
|
|
58
|
+
|
|
59
|
+
## Enforcement
|
|
60
|
+
|
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
62
|
+
reported to the community leaders responsible for enforcement at
|
|
63
|
+
krwhitley@gmail.com.
|
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
|
65
|
+
|
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
|
67
|
+
reporter of any incident.
|
|
68
|
+
|
|
69
|
+
## Enforcement Guidelines
|
|
70
|
+
|
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
|
73
|
+
|
|
74
|
+
### 1. Correction
|
|
75
|
+
|
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
77
|
+
unprofessional or unwelcome in the community.
|
|
78
|
+
|
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
|
82
|
+
|
|
83
|
+
### 2. Warning
|
|
84
|
+
|
|
85
|
+
**Community Impact**: A violation through a single incident or series
|
|
86
|
+
of actions.
|
|
87
|
+
|
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
|
92
|
+
like social media. Violating these terms may lead to a temporary or
|
|
93
|
+
permanent ban.
|
|
94
|
+
|
|
95
|
+
### 3. Temporary Ban
|
|
96
|
+
|
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
|
98
|
+
sustained inappropriate behavior.
|
|
99
|
+
|
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
+
communication with the community for a specified period of time. No public or
|
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
+
Violating these terms may lead to a permanent ban.
|
|
105
|
+
|
|
106
|
+
### 4. Permanent Ban
|
|
107
|
+
|
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
+
|
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within
|
|
113
|
+
the community.
|
|
114
|
+
|
|
115
|
+
## Attribution
|
|
116
|
+
|
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
+
version 2.0, available at
|
|
119
|
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
|
120
|
+
|
|
121
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
|
122
|
+
enforcement ladder](https://github.com/mozilla/diversity).
|
|
123
|
+
|
|
124
|
+
[homepage]: https://www.contributor-covenant.org
|
|
125
|
+
|
|
126
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
|
127
|
+
https://www.contributor-covenant.org/faq. Translations are available at
|
|
128
|
+
https://www.contributor-covenant.org/translations.
|
package/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Contributing to Itty
|
|
2
|
+
|
|
3
|
+
The [Open Source Guides](https://opensource.guide/) website has a collection of resources for individuals, communities, and companies. These resources help people who want to learn how to run and contribute to open source projects. Contributors and people new to open source alike will find the following guides especially useful:
|
|
4
|
+
|
|
5
|
+
- [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/)
|
|
6
|
+
- [Building Welcoming Communities](https://opensource.guide/building-community/)
|
|
7
|
+
|
|
8
|
+
## Bugs
|
|
9
|
+
|
|
10
|
+
We use [GitHub issues](https://github.com/kwhitley/itty-router/issues) for our public bugs. If you would like to report a problem, take a look around and see if someone already opened an issue about it. If you are certain this is a new unreported bug, you can submit a [bug report](#reporting-new-issues).
|
|
11
|
+
|
|
12
|
+
If you have questions about using itty, [contact us on Discord](https://discord.com/channels/832353585802903572), and we will do our best to answer your questions.
|
|
13
|
+
|
|
14
|
+
### Reporting new issues
|
|
15
|
+
|
|
16
|
+
When [opening a new issue](https://github.com/kwhitley/itty-router/issues/new/choose), always make sure to fill out the issue template. **This step is very important!** Not doing so may result in your issue not being managed in a timely fashion. Don't take this personally if this happens, and feel free to open a new issue once you've gathered all the information required by the template.
|
|
17
|
+
|
|
18
|
+
- **One issue, one bug:** Please report a single bug per issue.
|
|
19
|
+
- **Provide reproduction steps:** List all the steps necessary to reproduce the issue. The person reading your bug report should be able to follow these steps to reproduce your issue with minimal effort.
|
|
20
|
+
|
|
21
|
+
### Proposing a change
|
|
22
|
+
|
|
23
|
+
If you would like to request a new feature or enhancement but are not yet thinking about opening a pull request, you can also file an issue with [feature template](https://github.com/kwhitley/itty-router/issues/new?template=feature_request.yml).
|
|
24
|
+
|
|
25
|
+
If you're only fixing a bug, it's fine to submit a pull request right away, but we still recommend that you file an issue detailing what you're fixing. This is helpful in case we don't accept that specific fix but want to keep track of the issue.
|
|
26
|
+
|
|
27
|
+
Small pull requests are much easier to review and more likely to get merged.
|
|
28
|
+
|
|
29
|
+
### Installation
|
|
30
|
+
|
|
31
|
+
1. Ensure you have [npm](https://www.npmjs.com/get-npm) installed.
|
|
32
|
+
1. Ensure you have [yarn](https://classic.yarnpkg.com/lang/en/docs/install) installed.
|
|
33
|
+
1. After cloning the repository, run `yarn` in the root of the repository.
|
|
34
|
+
1. To start development, run `yarn dev`.
|
|
35
|
+
|
|
36
|
+
### Creating a branch
|
|
37
|
+
|
|
38
|
+
Fork [the repository](https://github.com/kwhitley/itty-router) and create your branch from `v4.x`. If you've never sent a GitHub pull request before, you can learn how from [this free video series](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github).
|
|
39
|
+
|
|
40
|
+
### Testing
|
|
41
|
+
|
|
42
|
+
A good test plan has the exact commands you ran and their output, provides screenshots or videos if the pull request changes UI.
|
|
43
|
+
|
|
44
|
+
- If you've changed APIs, update the documentation, including at the appropriate places within [itty.dev](https://itty.dev/itty-router).
|
|
45
|
+
|
|
46
|
+
#### Writing tests
|
|
47
|
+
|
|
48
|
+
All tests are located in adjacent `.spec.ts` files, next to the file being tested.
|
|
49
|
+
|
|
50
|
+
#### Running tests
|
|
51
|
+
|
|
52
|
+
1. To run test, run `yarn test`, or `yarn dev` for continuous testing (includes `--watch`).
|
|
53
|
+
|
|
54
|
+
### Style guide
|
|
55
|
+
|
|
56
|
+
[Eslint](https://eslint.org) will catch most styling issues that may exist in your code. You can check the status of your code styling by simply running `yarn lint`.
|
|
57
|
+
|
|
58
|
+
#### Code conventions
|
|
59
|
+
|
|
60
|
+
- `camelCase` for public variable names and methods.
|
|
61
|
+
- No abbreviated variable names - maximize readability and let the minification process do its thing later.
|
|
62
|
+
|
|
63
|
+
### Sending your pull request
|
|
64
|
+
|
|
65
|
+
Please make sure the following is done when submitting a pull request:
|
|
66
|
+
|
|
67
|
+
1. Describe your **test plan** in your pull request description. Make sure to test your changes.
|
|
68
|
+
1. Make sure your code lints (`yarn lint`).
|
|
69
|
+
1. Make sure your tests pass (`yarn test`).
|
|
70
|
+
|
|
71
|
+
All pull requests should be opened against the `v4.x` branch. Make sure the PR does only one thing, otherwise please split it.
|
|
72
|
+
|
|
73
|
+
#### Breaking changes
|
|
74
|
+
|
|
75
|
+
When adding a new breaking change, follow this template in your pull request:
|
|
76
|
+
|
|
77
|
+
```md
|
|
78
|
+
### New breaking change here
|
|
79
|
+
|
|
80
|
+
- **Who does this affect**:
|
|
81
|
+
- **How to migrate**:
|
|
82
|
+
- **Why make this breaking change**:
|
|
83
|
+
- **Severity (number of people affected x effort)**:
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
By contributing to itty, you agree that your contributions will be licensed under its [MIT license](https://github.com/kwhitley/itty-router/blob/master/LICENSE).
|
|
89
|
+
|
|
90
|
+
## Questions
|
|
91
|
+
|
|
92
|
+
Feel free to ask in [#itty-router](https://discord.com/channels/832353585802903572) on [Discord](https://discord.com/channels/832353585802903572) if you have questions about our process, how to proceed, etc.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Kevin R. Whitley
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
<br />
|
|
2
|
+
|
|
3
|
+
<p>
|
|
4
|
+
<a href="https://itty.dev/itty-sockets" target="_blank">
|
|
5
|
+
<img src="https://github.com/user-attachments/assets/cfe915d5-63ce-4297-83ef-316426c7af57" alt="itty-sockets" height="120" />
|
|
6
|
+
</a>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
[](https://npmjs.com/package/itty-sockets)
|
|
10
|
+
[](https://deno.bundlejs.com/?q=itty-sockets)
|
|
11
|
+
[](https://coveralls.io/github/kwhitley/itty-sockets)
|
|
12
|
+
[](https://github.com/kwhitley/itty-sockets/issues)
|
|
13
|
+
[](https://discord.gg/53vyrZAu9u)
|
|
14
|
+
|
|
15
|
+
### [Documentation](https://itty.dev/itty-sockets) | [Discord](https://discord.gg/53vyrZAu9u)
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
Tiny messaging client in under 400 bytes. No backend needed.
|
|
20
|
+
|
|
21
|
+
## Example
|
|
22
|
+
```ts
|
|
23
|
+
import { connect } from 'itty-sockets'
|
|
24
|
+
|
|
25
|
+
// create a channel instance
|
|
26
|
+
const foo = connect('foo')
|
|
27
|
+
|
|
28
|
+
// listen for messages
|
|
29
|
+
foo.listen(e => {
|
|
30
|
+
console.log(e.alias ?? e.uid, 'says', e.message, 'at', e.date)
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
// send some messages
|
|
34
|
+
room
|
|
35
|
+
.send('hello world!')
|
|
36
|
+
.send([1,2,3]) // no need to stringify
|
|
37
|
+
.send({ foo: 'bar' })
|
|
38
|
+
|
|
39
|
+
// or connect, send, and close - all in one call
|
|
40
|
+
room.push('this will send and close the connection')
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Features
|
|
44
|
+
|
|
45
|
+
- Simple and powerful API for sending and receiving messages & data
|
|
46
|
+
- Streamlines async race conditions
|
|
47
|
+
- No backend service needed. Ours is fast and stores/logs nothing at all
|
|
48
|
+
- Ultra-tiny. It's an itty library, after all
|
|
49
|
+
- Full TypeScript support (when imported)
|
|
50
|
+
|
|
51
|
+
## What is itty-sockets?
|
|
52
|
+
|
|
53
|
+
`itty-sockets` is a tiny messaging client that simplifies data/message transmission between users/connections.
|
|
54
|
+
It's powered by [ittysockets.io](https://ittysockets.io), a free, fast, and private public service. The idea is simple:
|
|
55
|
+
|
|
56
|
+
1. Connect to a channel using a unique name (you choose it)
|
|
57
|
+
2. Send messages to the channel (from one or more parties)
|
|
58
|
+
3. Listen for messages in the channel (from one or more parties)
|
|
59
|
+
4. Profit.
|
|
60
|
+
|
|
61
|
+
This is an easy way to transmit messages between clients, but comes with limitations and considerations:
|
|
62
|
+
|
|
63
|
+
1. **There is no history/replay.** It's a live stream.
|
|
64
|
+
2. **We don't authenticate.** Itty Sockets leverages security merely through obfuscation (a near-infinite number of channel names). Use a secure channel name and/or encode your payloads if concerned about eavesdropping. Add your own authentication layer, if needed.
|
|
65
|
+
3. **There are no guarantees of delivery.** Itty Sockets is not a traditional messaging system. It's a public service that is provided without any guarantees of delivery, order, or persistence. Use it for real-time communication, not for mission-critical data.
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
### Privacy Concerns
|
|
70
|
+
**We do not store any messages or data**
|
|
71
|
+
There is intentionally no message logging or tracking of any kind. It's easier for us that way, and safer for you.
|
|
72
|
+
|
|
73
|
+
## Browser Usage
|
|
74
|
+
|
|
75
|
+
If you want to send/receive messages from the browser (e.g. for sending information from one web page or tab to another), copy and paste this snippet directly into your browser console, then use as normal.
|
|
76
|
+
|
|
77
|
+
<!-- BEGIN SNIPPET -->
|
|
78
|
+
```ts
|
|
79
|
+
let connect=(e,s={})=>{let t,n=[],o=[],a=0,r=()=>{t||(t=new WebSocket(`wss://ittysockets.io/r/${e??""}?${new URLSearchParams(s)}`),t.onopen=()=>{for(;n.length;)t?.send(n.shift());a&&t?.close()},t.onmessage=(e,s=JSON.parse(e.data))=>{for(let e of o)e({...s,date:new Date(s.date)})},t.onclose=()=>(a=0,t=null))};return new Proxy(r,{get:(e,s,l)=>({ws:t,send:(e,s)=>(e=JSON.stringify(e),e=s?`@@${s}@@${e}`:e,1==t?.readyState?t.send(e)??l:(n.push(e),r()??l)),push:(e,s)=>(a=1,l.send(e,s)),listen:(e,s)=>(o.push((t=>(!s||s(t))&&e(t))),r()??l),close:()=>(1==t?.readyState?t.close():a=1,l)}[s])})};
|
|
80
|
+
```
|
|
81
|
+
<!-- END SNIPPET -->
|
|
82
|
+
|
|
83
|
+
afterwards:
|
|
84
|
+
```ts
|
|
85
|
+
// send a message on connect 'foo'
|
|
86
|
+
connect('foo').push('hello world!')
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## API
|
|
90
|
+
|
|
91
|
+
| METHOD | DESCRIPTION | EXAMPLE |
|
|
92
|
+
| --- | --- | --- |
|
|
93
|
+
| **connect(id, options)** | Creates a new connect | `connect('foo')` |
|
|
94
|
+
| **send(message)** | Sends a message to the room | `room.send({ type: 'chat', text: 'hello' })` |
|
|
95
|
+
| **push(message)** | Sends a message and closes the connection | `room.push({ type: 'goodbye' })` |
|
|
96
|
+
| **listen(fn)** | Adds a message listener | `room.listen(msg => console.log(msg))` |
|
|
97
|
+
| **close()** | Closes the connection | `room.close()` |
|
|
98
|
+
|
|
99
|
+
### Available Options
|
|
100
|
+
|
|
101
|
+
| OPTION | DESCRIPTION | DEFAULT | EXAMPLE |
|
|
102
|
+
| --- | --- | --- | --- |
|
|
103
|
+
| **alias** | An optional display name for the connection | `undefined` | `{ alias: 'Kevin' }` |
|
|
104
|
+
| **echo** | Whether to echo messages back to the sender | `false` | `{ echo: true }` |
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
## Message Format
|
|
108
|
+
```ts
|
|
109
|
+
type Message = {
|
|
110
|
+
id: string // unique message ID
|
|
111
|
+
date: Date // JavaScript Date object
|
|
112
|
+
message: any // the message payload
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
package/bun.lockb
ADDED
|
Binary file
|
package/bunfig.toml
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import typescriptEslint from '@typescript-eslint/eslint-plugin'
|
|
2
|
+
import tsParser from '@typescript-eslint/parser'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import js from '@eslint/js'
|
|
6
|
+
import { FlatCompat } from '@eslint/eslintrc'
|
|
7
|
+
|
|
8
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
9
|
+
const __dirname = path.dirname(__filename)
|
|
10
|
+
const compat = new FlatCompat({
|
|
11
|
+
baseDirectory: __dirname,
|
|
12
|
+
recommendedConfig: js.configs.recommended,
|
|
13
|
+
allConfig: js.configs.all
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
export default [...compat.extends(
|
|
17
|
+
'eslint:recommended',
|
|
18
|
+
'plugin:@typescript-eslint/eslint-recommended',
|
|
19
|
+
'plugin:@typescript-eslint/recommended',
|
|
20
|
+
), {
|
|
21
|
+
plugins: {
|
|
22
|
+
'@typescript-eslint': typescriptEslint,
|
|
23
|
+
},
|
|
24
|
+
|
|
25
|
+
languageOptions: {
|
|
26
|
+
parser: tsParser,
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
rules: {
|
|
30
|
+
'@typescript-eslint/no-empty-function': 'off',
|
|
31
|
+
'@typescript-eslint/no-explicit-any': 'off',
|
|
32
|
+
'@typescript-eslint/ban-types': 'off',
|
|
33
|
+
'@typescript-eslint/ban-ts-comment': 'off',
|
|
34
|
+
'linebreak-style': ['error', 'unix'],
|
|
35
|
+
'prefer-const': 'off',
|
|
36
|
+
|
|
37
|
+
quotes: ['error', 'single', {
|
|
38
|
+
allowTemplateLiterals: true,
|
|
39
|
+
}],
|
|
40
|
+
|
|
41
|
+
semi: ['error', 'never'],
|
|
42
|
+
},
|
|
43
|
+
}]
|
package/package.json
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "itty-sockets",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "An easier way to handle WebSockets, in an itty package.",
|
|
5
|
+
"main": "./sockets.js",
|
|
6
|
+
"module": "./sockets.mjs",
|
|
7
|
+
"types": "./sockets.d.ts",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"dev": "bun test --watch",
|
|
10
|
+
"lint": "bun eslint src",
|
|
11
|
+
"verify": "echo 'verifying module...' && bun run build && bun test",
|
|
12
|
+
"prerelease": "bun run verify",
|
|
13
|
+
"prerelease:next": "bun run verify",
|
|
14
|
+
"prebuild": "rimraf dist && mkdir dist",
|
|
15
|
+
"build": "rollup -c && node scripts/inject-snippet.mjs",
|
|
16
|
+
"release": "release --tag --push --patch --src=dist",
|
|
17
|
+
"release:next": "release --tag --push --type=next --src=dist"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"websockets",
|
|
21
|
+
"realtime",
|
|
22
|
+
"free",
|
|
23
|
+
"p2p"
|
|
24
|
+
],
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "git+https://github.com/kwhitley/itty-sockets.git"
|
|
28
|
+
},
|
|
29
|
+
"author": "Kevin R. Whitley <krwhitley@gmail.com>",
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/kwhitley/itty-sockets/issues"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
36
|
+
"@rollup/plugin-typescript": "^11.1.6",
|
|
37
|
+
"@types/bun": "^1.2.3",
|
|
38
|
+
"@typescript-eslint/eslint-plugin": "^8.18.0",
|
|
39
|
+
"@typescript-eslint/parser": "^8.18.0",
|
|
40
|
+
"eslint": "^9.17.0",
|
|
41
|
+
"globby": "^14.1.0",
|
|
42
|
+
"rimraf": "^6.0.1",
|
|
43
|
+
"rollup": "^4.28.1",
|
|
44
|
+
"rollup-plugin-bundle-size": "^1.0.3",
|
|
45
|
+
"rollup-plugin-copy": "^3.5.0",
|
|
46
|
+
"typescript": "^5.7.2",
|
|
47
|
+
"yarn-release": "^1.10.6"
|
|
48
|
+
},
|
|
49
|
+
"exports": {
|
|
50
|
+
".": {
|
|
51
|
+
"import": "./index.mjs",
|
|
52
|
+
"require": "./index.js",
|
|
53
|
+
"types": "./index.d.ts"
|
|
54
|
+
},
|
|
55
|
+
"./connect": {
|
|
56
|
+
"import": "./connect.mjs",
|
|
57
|
+
"require": "./connect.js",
|
|
58
|
+
"types": "./connect.d.ts"
|
|
59
|
+
},
|
|
60
|
+
"./ws": {
|
|
61
|
+
"import": "./ws.mjs",
|
|
62
|
+
"require": "./ws.js",
|
|
63
|
+
"types": "./ws.d.ts"
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import terser from '@rollup/plugin-terser'
|
|
2
|
+
import typescript from '@rollup/plugin-typescript'
|
|
3
|
+
import fs from 'fs-extra'
|
|
4
|
+
import { globby } from 'globby'
|
|
5
|
+
import bundleSize from 'rollup-plugin-bundle-size'
|
|
6
|
+
import copy from 'rollup-plugin-copy'
|
|
7
|
+
|
|
8
|
+
// scan files to build
|
|
9
|
+
const files = (await globby('./src/*.ts', {
|
|
10
|
+
ignore: ['**/*.spec.ts', '**/types.ts'],
|
|
11
|
+
})).map(path => ({
|
|
12
|
+
path,
|
|
13
|
+
shortPath: path.replace(/(\/src)|(\.ts)/g, '').replace('./index', '.'),
|
|
14
|
+
esm: path.replace('/src/', '/dist/').replace('.ts', '.mjs'),
|
|
15
|
+
cjs: path.replace('/src/', '/dist/').replace('.ts', '.js'),
|
|
16
|
+
types: path.replace('/src/', '/dist/').replace('.ts', '.d.ts'),
|
|
17
|
+
})).sort((a, b) => a.shortPath.toLowerCase() < b.shortPath.toLowerCase() ? -1 : 1)
|
|
18
|
+
|
|
19
|
+
// read original package.json
|
|
20
|
+
const pkg = await fs.readJSON('./package.json')
|
|
21
|
+
|
|
22
|
+
// create updated exports list from build files
|
|
23
|
+
pkg.exports = files.reduce((acc, file) => {
|
|
24
|
+
acc[file.shortPath] = {
|
|
25
|
+
import: file.esm.replace('/dist', ''),
|
|
26
|
+
require: file.cjs.replace('/dist', ''),
|
|
27
|
+
types: file.types.replace('/dist', ''),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return acc
|
|
31
|
+
}, {})
|
|
32
|
+
|
|
33
|
+
// write updated package.json
|
|
34
|
+
await fs.writeJSON('./package.json', pkg, { spaces: 2 })
|
|
35
|
+
|
|
36
|
+
export default async () => {
|
|
37
|
+
console.log(files.map(f => f.path))
|
|
38
|
+
|
|
39
|
+
// export base files
|
|
40
|
+
return [
|
|
41
|
+
...files.map(file => ({
|
|
42
|
+
input: file.path,
|
|
43
|
+
output: [
|
|
44
|
+
{
|
|
45
|
+
format: 'esm',
|
|
46
|
+
file: file.esm,
|
|
47
|
+
sourcemap: false,
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
format: 'cjs',
|
|
51
|
+
file: file.cjs,
|
|
52
|
+
sourcemap: false,
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
plugins: [
|
|
56
|
+
typescript({ sourceMap: false }),
|
|
57
|
+
terser(),
|
|
58
|
+
bundleSize(),
|
|
59
|
+
copy({
|
|
60
|
+
targets: [
|
|
61
|
+
{
|
|
62
|
+
src: ['LICENSE'],
|
|
63
|
+
dest: 'dist',
|
|
64
|
+
},
|
|
65
|
+
],
|
|
66
|
+
}),
|
|
67
|
+
],
|
|
68
|
+
})),
|
|
69
|
+
{
|
|
70
|
+
input: 'src/connect.ts',
|
|
71
|
+
output: {
|
|
72
|
+
file: 'dist/connect.snippet.js',
|
|
73
|
+
format: 'esm',
|
|
74
|
+
name: 'connect',
|
|
75
|
+
},
|
|
76
|
+
plugins: [
|
|
77
|
+
typescript(),
|
|
78
|
+
terser(),
|
|
79
|
+
],
|
|
80
|
+
},
|
|
81
|
+
]
|
|
82
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
|
|
3
|
+
const transformCode = code => code
|
|
4
|
+
.replace(/^const\s+(\w+)\s*=/, 'let connect=')
|
|
5
|
+
.replace(/;export\s*{[^}]+};?\s*$/, ';')
|
|
6
|
+
|
|
7
|
+
const snippet = fs.readFileSync('dist/connect.snippet.js', 'utf-8')
|
|
8
|
+
const transformed = transformCode(snippet).trim()
|
|
9
|
+
|
|
10
|
+
// Write transformed code to both files
|
|
11
|
+
fs.writeFileSync('dist/connect.snippet.js', transformed)
|
|
12
|
+
|
|
13
|
+
const readme = fs.readFileSync('README.md', 'utf-8')
|
|
14
|
+
const newReadme = readme.replace(
|
|
15
|
+
/(<!-- BEGIN SNIPPET -->[\r\n]+```(?:js|ts)[\r\n]).*?([\r\n]```[\r\n]+<!-- END SNIPPET -->)/s,
|
|
16
|
+
`$1${transformed}$2`
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
fs.writeFileSync('README.md', newReadme)
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
|
|
2
|
+
import { connect, MessageEvent, type Connection } from './connect'
|
|
3
|
+
|
|
4
|
+
describe('connect', () => {
|
|
5
|
+
const getChannelID = () => 'itty:itty-sockets:test-' + Math.random().toString(36).slice(2)
|
|
6
|
+
const setup = () => connect(getChannelID(), { echo: true })
|
|
7
|
+
|
|
8
|
+
const tests = [
|
|
9
|
+
{
|
|
10
|
+
group: 'methods',
|
|
11
|
+
cases: [
|
|
12
|
+
{
|
|
13
|
+
name: 'exposes .send, .push, .listen, .close',
|
|
14
|
+
run: (channel: Connection) => {
|
|
15
|
+
for (const method of ['send', 'push', 'listen', 'close']) {
|
|
16
|
+
expect(typeof channel[method]).toBe('function')
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
group: 'server options',
|
|
24
|
+
cases: [
|
|
25
|
+
{
|
|
26
|
+
name: 'echo > sends messages back to sender',
|
|
27
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
28
|
+
const channel = connect(getChannelID(), { echo: true })
|
|
29
|
+
|
|
30
|
+
channel.listen(msg => {
|
|
31
|
+
expect(msg.message).toBe('test')
|
|
32
|
+
resolve()
|
|
33
|
+
})
|
|
34
|
+
channel.send('test')
|
|
35
|
+
})
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: 'as > sets alias for messages',
|
|
39
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
40
|
+
const channel = connect(getChannelID(), { echo: true, as: 'test-user' })
|
|
41
|
+
const timeout = setTimeout(() => reject(new Error('No message received')), 150)
|
|
42
|
+
|
|
43
|
+
channel.listen(msg => {
|
|
44
|
+
clearTimeout(timeout)
|
|
45
|
+
expect(msg.alias).toBe('test-user')
|
|
46
|
+
resolve()
|
|
47
|
+
})
|
|
48
|
+
channel.send('test')
|
|
49
|
+
})
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
group: 'message handling',
|
|
55
|
+
cases: [
|
|
56
|
+
{
|
|
57
|
+
name: 'MessageEvent > includes expected fields',
|
|
58
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
59
|
+
const channel = setup()
|
|
60
|
+
const timeout = setTimeout(() => reject(new Error('No message received')), 150)
|
|
61
|
+
|
|
62
|
+
channel.listen(msg => {
|
|
63
|
+
clearTimeout(timeout)
|
|
64
|
+
expect(msg.date instanceof Date).toBe(true)
|
|
65
|
+
expect(typeof msg.uid).toBe('string')
|
|
66
|
+
expect(msg.message).toBe('test')
|
|
67
|
+
resolve()
|
|
68
|
+
})
|
|
69
|
+
channel.send('test')
|
|
70
|
+
})
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: 'handles conditional message listening',
|
|
74
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
75
|
+
const channel = setup()
|
|
76
|
+
let receivedCount = 0
|
|
77
|
+
const timeout = setTimeout(() => reject(new Error('Test timeout')), 150)
|
|
78
|
+
|
|
79
|
+
channel.listen(
|
|
80
|
+
msg => {
|
|
81
|
+
receivedCount++
|
|
82
|
+
if (receivedCount === 1) {
|
|
83
|
+
clearTimeout(timeout)
|
|
84
|
+
resolve()
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
msg => msg.message.type === 'test'
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
channel.send({ type: 'test' })
|
|
91
|
+
channel.send({ type: 'other' })
|
|
92
|
+
})
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: 'when predicate blocks messages',
|
|
96
|
+
run: (channel: Connection) => new Promise<void>((resolve) => {
|
|
97
|
+
let called = false
|
|
98
|
+
channel
|
|
99
|
+
.listen(
|
|
100
|
+
() => { called = true },
|
|
101
|
+
() => false // when predicate always returns false
|
|
102
|
+
)
|
|
103
|
+
.send('test')
|
|
104
|
+
|
|
105
|
+
setTimeout(() => {
|
|
106
|
+
expect(called).toBe(false)
|
|
107
|
+
resolve()
|
|
108
|
+
}, 100)
|
|
109
|
+
})
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
name: 'sends private messages to recipient',
|
|
113
|
+
run: (channel: Connection) => new Promise<void>((resolve, reject) => {
|
|
114
|
+
const recipient = 'user-' + Math.random().toString(36).slice(2)
|
|
115
|
+
const message = 'private-message'
|
|
116
|
+
|
|
117
|
+
channel
|
|
118
|
+
.listen(e => {
|
|
119
|
+
expect(e.uid).toBeUndefined()
|
|
120
|
+
expect(e.message).toContain(recipient)
|
|
121
|
+
resolve()
|
|
122
|
+
})
|
|
123
|
+
.send(message, recipient)
|
|
124
|
+
})
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
name: 'handles multiple listeners for same message',
|
|
128
|
+
run: (channel: Connection) => new Promise<void>((resolve) => {
|
|
129
|
+
let count = 0
|
|
130
|
+
const listener1 = () => count++
|
|
131
|
+
const listener2 = () => count++
|
|
132
|
+
|
|
133
|
+
channel
|
|
134
|
+
.listen(listener1)
|
|
135
|
+
.listen(listener2)
|
|
136
|
+
.send('test')
|
|
137
|
+
|
|
138
|
+
setTimeout(() => {
|
|
139
|
+
expect(count).toBe(2)
|
|
140
|
+
resolve()
|
|
141
|
+
}, 100)
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
]
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
group: 'message queueing',
|
|
148
|
+
cases: [
|
|
149
|
+
{
|
|
150
|
+
name: 'processes queued messages in order',
|
|
151
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
152
|
+
const channel = setup()
|
|
153
|
+
const messages = ['first', 'second', 'third']
|
|
154
|
+
const received: any[] = []
|
|
155
|
+
const timeout = setTimeout(() => reject(new Error('Queue timeout')), 150)
|
|
156
|
+
|
|
157
|
+
channel.listen(msg => {
|
|
158
|
+
received.push(msg.message)
|
|
159
|
+
if (received.length === messages.length) {
|
|
160
|
+
clearTimeout(timeout)
|
|
161
|
+
expect(received).toEqual(messages)
|
|
162
|
+
resolve()
|
|
163
|
+
}
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
messages.forEach(msg => channel.send(msg))
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
]
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
group: 'push behavior',
|
|
173
|
+
cases: [
|
|
174
|
+
{
|
|
175
|
+
name: 'sends message and closes immediately',
|
|
176
|
+
run: async () => {
|
|
177
|
+
const cid = getChannelID()
|
|
178
|
+
const channel = connect(cid)
|
|
179
|
+
const receiver = connect(cid)
|
|
180
|
+
const message = 'push-test'
|
|
181
|
+
|
|
182
|
+
return new Promise<void>((resolve, reject) => {
|
|
183
|
+
const timeout = setTimeout(() => reject(new Error('Push timeout')), 150)
|
|
184
|
+
|
|
185
|
+
receiver.listen(msg => {
|
|
186
|
+
clearTimeout(timeout)
|
|
187
|
+
expect(msg.message).toBe(message)
|
|
188
|
+
|
|
189
|
+
setTimeout(() => {
|
|
190
|
+
expect(channel.ws).toBeNull()
|
|
191
|
+
resolve()
|
|
192
|
+
}, 50)
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
channel.push(message)
|
|
196
|
+
})
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
]
|
|
200
|
+
}
|
|
201
|
+
]
|
|
202
|
+
|
|
203
|
+
// Generate tests from data structure
|
|
204
|
+
for (const { group, cases } of tests) {
|
|
205
|
+
describe(group, () => {
|
|
206
|
+
for (const { name, run } of cases) {
|
|
207
|
+
it(name, () => run(setup()))
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
})
|
package/src/connect.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export type AllowedProperty = 'ws' | 'send' | 'push' | 'listen' | 'close'
|
|
2
|
+
|
|
3
|
+
export type MessageEvent<MessageType = any> = {
|
|
4
|
+
date: Date
|
|
5
|
+
uid?: string
|
|
6
|
+
alias?: string
|
|
7
|
+
message: MessageType
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export type SendMessage = <MessageFormat = any>(message: MessageFormat, recipient?: string) => Connection
|
|
11
|
+
|
|
12
|
+
export type Connection = {
|
|
13
|
+
ws?: WebSocket,
|
|
14
|
+
send: SendMessage,
|
|
15
|
+
push: SendMessage,
|
|
16
|
+
listen: <MessageType = any>(
|
|
17
|
+
listener: (event: MessageEvent<MessageType>) => any,
|
|
18
|
+
when?: (event: MessageEvent<MessageType>) => any,
|
|
19
|
+
) => Connection,
|
|
20
|
+
close: () => Connection,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const connect = (id: string, options: Record<string, any> = {}): Connection => {
|
|
24
|
+
let ws: WebSocket | null,
|
|
25
|
+
queue: string[] = [],
|
|
26
|
+
listeners: Array<(event: MessageEvent) => any> = [],
|
|
27
|
+
closeAfterSend = 0
|
|
28
|
+
|
|
29
|
+
let connect = () => {
|
|
30
|
+
if (ws) return // Don't reconnect if already opening/open
|
|
31
|
+
|
|
32
|
+
ws = new WebSocket(`wss://ittysockets.io/r/${id??''}?${new URLSearchParams(options)}`)
|
|
33
|
+
|
|
34
|
+
ws.onopen = () => {
|
|
35
|
+
while (queue.length) ws?.send(queue.shift()!)
|
|
36
|
+
if (closeAfterSend) ws?.close()
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
ws.onmessage = (
|
|
40
|
+
event: any,
|
|
41
|
+
parsed = JSON.parse(event.data),
|
|
42
|
+
) => {
|
|
43
|
+
for (let listener of listeners)
|
|
44
|
+
listener({ ...parsed, date: new Date(parsed.date) })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
ws.onclose = () => (closeAfterSend = 0, ws = null)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// @ts-ignore
|
|
51
|
+
return new Proxy(connect, {
|
|
52
|
+
get: (_, key: AllowedProperty, __) =>
|
|
53
|
+
({
|
|
54
|
+
ws,
|
|
55
|
+
send: (message: any, recipient?: string) => {
|
|
56
|
+
message = JSON.stringify(message)
|
|
57
|
+
message = recipient ? `@@${recipient}@@${message}` : message
|
|
58
|
+
if (ws?.readyState == 1) return ws.send(message) ?? __
|
|
59
|
+
queue.push(message)
|
|
60
|
+
|
|
61
|
+
return connect() ?? __
|
|
62
|
+
},
|
|
63
|
+
push: (message: any, recipient?: string) => {
|
|
64
|
+
closeAfterSend = 1
|
|
65
|
+
return __.send(message, recipient)
|
|
66
|
+
},
|
|
67
|
+
listen: <MessageType = any>(
|
|
68
|
+
listener: (event: MessageEvent<MessageType>) => any,
|
|
69
|
+
when?: (event: MessageEvent<MessageType>) => boolean
|
|
70
|
+
) => {
|
|
71
|
+
listeners.push((event: MessageEvent<any>) =>
|
|
72
|
+
(!when || when(event as MessageEvent<MessageType>)) && listener(event as MessageEvent<MessageType>)
|
|
73
|
+
)
|
|
74
|
+
return connect() ?? __
|
|
75
|
+
},
|
|
76
|
+
close: () => (ws?.readyState == 1 ? ws.close() : (closeAfterSend = 1), __)
|
|
77
|
+
})[key]
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// type FooMessage = {
|
|
82
|
+
// name: string
|
|
83
|
+
// age: number
|
|
84
|
+
// pets: string[]
|
|
85
|
+
// }
|
|
86
|
+
// type XYMessage = {
|
|
87
|
+
// x: number
|
|
88
|
+
// y: number
|
|
89
|
+
// }
|
|
90
|
+
|
|
91
|
+
// connect('test')
|
|
92
|
+
// .listen<FooMessage>(({ message }) => {
|
|
93
|
+
// console.log(message.name)
|
|
94
|
+
// }, (msg) => msg.message.name)
|
|
95
|
+
// .listen<XYMessage>(({ message }) => {
|
|
96
|
+
// console.log(message.x, message.y)
|
|
97
|
+
// }, (msg) => msg.message.x !== undefined)
|
|
98
|
+
// .listen<{ x: number }>(e => e.message.foo == 'bar')
|
|
99
|
+
// .push<{ x: number }>({ foo: 'bar' })
|
package/src/index.ts
ADDED
package/src/ws.spec.ts
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { ws, type Connection, type ConnectionOptions } from './ws'
|
|
3
|
+
|
|
4
|
+
describe('ws', () => {
|
|
5
|
+
const getURL = (id: string) =>
|
|
6
|
+
`wss://ittysockets.io/r/itty:itty-sockets:test-${id}?echo=true`
|
|
7
|
+
|
|
8
|
+
const setup = (options: ConnectionOptions = {}) => {
|
|
9
|
+
const id = Math.random().toString(36).slice(2)
|
|
10
|
+
return ws(getURL(id), options)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const tests = [
|
|
14
|
+
{
|
|
15
|
+
group: 'basics',
|
|
16
|
+
cases: [
|
|
17
|
+
{
|
|
18
|
+
name: 'is a function',
|
|
19
|
+
run: () => expect(typeof ws).toBe('function')
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
name: 'returns proxy with methods',
|
|
23
|
+
run: conn => ['send', 'push', 'listen', 'close'].forEach(
|
|
24
|
+
method => expect(typeof conn[method]).toBe('function')
|
|
25
|
+
)
|
|
26
|
+
}
|
|
27
|
+
]
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
group: 'connection behavior',
|
|
31
|
+
cases: [
|
|
32
|
+
{
|
|
33
|
+
name: 'does not connect until triggered',
|
|
34
|
+
run: conn => expect(conn.ws).toBeUndefined()
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'exposes raw websocket after connection',
|
|
38
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
39
|
+
const conn = setup()
|
|
40
|
+
const timeout = setTimeout(() => reject(new Error('Connection timeout')), 150)
|
|
41
|
+
|
|
42
|
+
conn.listen(() => {
|
|
43
|
+
clearTimeout(timeout)
|
|
44
|
+
expect(conn.ws instanceof WebSocket).toBe(true)
|
|
45
|
+
expect(typeof conn.ws?.send).toBe('function')
|
|
46
|
+
expect(typeof conn.ws?.close).toBe('function')
|
|
47
|
+
resolve()
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
conn.send('test')
|
|
51
|
+
})
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: 'reconnects after close',
|
|
55
|
+
run: () => {
|
|
56
|
+
const conn = setup({ json: true })
|
|
57
|
+
conn
|
|
58
|
+
.listen((e) => {
|
|
59
|
+
if (e.message === 'end') {
|
|
60
|
+
expect(e.message).toBe('end')
|
|
61
|
+
}
|
|
62
|
+
})
|
|
63
|
+
.send('start')
|
|
64
|
+
.close()
|
|
65
|
+
|
|
66
|
+
setTimeout(() => {
|
|
67
|
+
conn.send('end')
|
|
68
|
+
}, 50)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
]
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
group: 'message handling',
|
|
75
|
+
cases: [
|
|
76
|
+
{
|
|
77
|
+
name: 'notifies listeners',
|
|
78
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
79
|
+
const conn = setup({ json: true })
|
|
80
|
+
const timeout = setTimeout(() => reject(new Error('No message received')), 150)
|
|
81
|
+
|
|
82
|
+
conn.listen(e => {
|
|
83
|
+
clearTimeout(timeout)
|
|
84
|
+
expect(e.message).toBe('test-message')
|
|
85
|
+
resolve()
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
conn.send('test-message')
|
|
89
|
+
})
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: 'handles json option',
|
|
93
|
+
run: () => new Promise<void>((resolve, reject) => {
|
|
94
|
+
const conn = ws(getURL(Math.random().toString(36).slice(2)), { json: true })
|
|
95
|
+
const data = { hello: 'world' }
|
|
96
|
+
const timeout = setTimeout(() => reject(new Error('No message received')), 150)
|
|
97
|
+
|
|
98
|
+
conn.listen(e => {
|
|
99
|
+
clearTimeout(timeout)
|
|
100
|
+
expect(e.message).toEqual(data)
|
|
101
|
+
resolve()
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
conn.send(data)
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
]
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
group: 'push behavior',
|
|
111
|
+
cases: [
|
|
112
|
+
{
|
|
113
|
+
name: 'sends message and closes',
|
|
114
|
+
run: async () => {
|
|
115
|
+
const id = Math.random().toString(36).slice(2)
|
|
116
|
+
const sender = ws(getURL(id), { json: true })
|
|
117
|
+
const receiver = ws(getURL(id), { json: true })
|
|
118
|
+
const message = 'push-test'
|
|
119
|
+
|
|
120
|
+
return new Promise<void>((resolve, reject) => {
|
|
121
|
+
const timeout = setTimeout(() => reject(new Error('Push timeout')), 150)
|
|
122
|
+
|
|
123
|
+
receiver.listen(e => {
|
|
124
|
+
clearTimeout(timeout)
|
|
125
|
+
expect(e.message).toBe(message)
|
|
126
|
+
|
|
127
|
+
setTimeout(() => {
|
|
128
|
+
expect(sender.ws).toBeNull()
|
|
129
|
+
resolve()
|
|
130
|
+
}, 50)
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
sender.push(message)
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
]
|
|
138
|
+
}
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
// Generate tests from data structure
|
|
142
|
+
for (const { group, cases } of tests) {
|
|
143
|
+
describe(group, () => {
|
|
144
|
+
for (const { name, run } of cases) {
|
|
145
|
+
it(name, () => run(setup()))
|
|
146
|
+
}
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
})
|
package/src/ws.ts
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
|
|
2
|
+
type AllowedProperty = 'ws' | 'send' | 'push' | 'listen' | 'close'
|
|
3
|
+
|
|
4
|
+
type SendMessage = <MessageFormat = any>(message: MessageFormat) => Connection
|
|
5
|
+
|
|
6
|
+
export type Connection = {
|
|
7
|
+
ws?: WebSocket | null,
|
|
8
|
+
send: SendMessage,
|
|
9
|
+
push: SendMessage,
|
|
10
|
+
listen: <MessageType = any>(
|
|
11
|
+
listener: (message: MessageType) => any,
|
|
12
|
+
when?: (message: MessageType) => any,
|
|
13
|
+
) => Connection,
|
|
14
|
+
close: () => Connection,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type ConnectionOptions = {
|
|
18
|
+
json?: boolean,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const ws = (url: string, options: ConnectionOptions = {}): Connection => {
|
|
22
|
+
let ws: WebSocket | null,
|
|
23
|
+
queue: string[] = [],
|
|
24
|
+
listeners: Array<(message: any) => any> = [],
|
|
25
|
+
closeAfterSend = 0
|
|
26
|
+
|
|
27
|
+
let connect = () => {
|
|
28
|
+
if (ws) return // Don't reconnect if already opening/open
|
|
29
|
+
ws = new WebSocket(url)
|
|
30
|
+
|
|
31
|
+
ws.onopen = () => {
|
|
32
|
+
while (queue.length) ws?.send(queue.shift()!)
|
|
33
|
+
if (closeAfterSend) ws?.close()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
ws.onmessage = (
|
|
37
|
+
event: MessageEvent,
|
|
38
|
+
message = options.json ? JSON.parse(event.data) : event.data,
|
|
39
|
+
) => {
|
|
40
|
+
for (let listener of listeners)
|
|
41
|
+
listener(message)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
ws.onclose = () => (closeAfterSend = 0, ws = null)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// @ts-ignore
|
|
48
|
+
return new Proxy(connect, {
|
|
49
|
+
get: (_, key: AllowedProperty, __) =>
|
|
50
|
+
({
|
|
51
|
+
ws,
|
|
52
|
+
send: (message: any) => {
|
|
53
|
+
message = options.json ? JSON.stringify(message) : message
|
|
54
|
+
if (ws?.readyState == 1) return ws.send(message) ?? __
|
|
55
|
+
queue.push(message)
|
|
56
|
+
return connect() ?? __
|
|
57
|
+
},
|
|
58
|
+
push: (message: any) => {
|
|
59
|
+
closeAfterSend = 1
|
|
60
|
+
return __.send(message)
|
|
61
|
+
},
|
|
62
|
+
listen: <T = any>(listener: (message: T) => any, when?: (message: T) => any) => {
|
|
63
|
+
listeners.push(msg => (!when || when(msg)) && listener(msg))
|
|
64
|
+
return connect() ?? __
|
|
65
|
+
},
|
|
66
|
+
// @ts-ignore
|
|
67
|
+
close: () => (ws?.readyState == 1 ? ws.close() : (closeAfterSend = 1), __)
|
|
68
|
+
})[key]
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// type CustomMessage = {
|
|
73
|
+
// foo: string,
|
|
74
|
+
// age: number,
|
|
75
|
+
// }
|
|
76
|
+
|
|
77
|
+
// type XYMessage = {
|
|
78
|
+
// x: number,
|
|
79
|
+
// y: number,
|
|
80
|
+
// }
|
|
81
|
+
|
|
82
|
+
// const checker = (message: XYMessage) => message.age === 1
|
|
83
|
+
|
|
84
|
+
// ws('wss://localhost:8080', { json: true })
|
|
85
|
+
// .listen<CustomMessage>(message => {
|
|
86
|
+
// console.log(message.foo)
|
|
87
|
+
// }, checker)
|
|
88
|
+
// .send<{ x: number }>({ foo: 'bar' })
|
|
89
|
+
// .push<{ x: number }>({ foo: 'bar' })
|
package/test.ts
ADDED
|
File without changes
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"allowJs": true,
|
|
4
|
+
"allowSyntheticDefaultImports": true,
|
|
5
|
+
"baseUrl": "src",
|
|
6
|
+
"declaration": true,
|
|
7
|
+
"sourceMap": false,
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"inlineSourceMap": false,
|
|
10
|
+
"lib": ["esnext", "es2015", "dom"],
|
|
11
|
+
"listEmittedFiles": false,
|
|
12
|
+
"listFiles": false,
|
|
13
|
+
"noFallthroughCasesInSwitch": true,
|
|
14
|
+
"pretty": true,
|
|
15
|
+
// "moduleResolution": "nodeNext", // disabled to be compatible with module: "esnext"
|
|
16
|
+
// "resolveJsonModule": true, // disabled to be compatible with module: "esnext"
|
|
17
|
+
"rootDir": "src",
|
|
18
|
+
"skipLibCheck": true,
|
|
19
|
+
"strict": true,
|
|
20
|
+
"traceResolution": false,
|
|
21
|
+
"outDir": "",
|
|
22
|
+
"target": "esnext",
|
|
23
|
+
"module": "esnext"
|
|
24
|
+
},
|
|
25
|
+
"exclude": ["node_modules", "dist", "**/*.spec.ts", "examples"],
|
|
26
|
+
"include": ["src", "src/seconds.ts"]
|
|
27
|
+
}
|