@beesolve/realtime-core 0.0.0 → 0.1.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/DOCS.md +19 -0
- package/README.md +58 -3
- package/dist/index.d.ts +51 -0
- package/dist/index.js +86 -0
- package/docs/how-to/channels-and-validation.md +73 -0
- package/package.json +26 -6
package/DOCS.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# @beesolve/realtime-core - Documentation
|
|
2
|
+
|
|
3
|
+
**Keywords:** realtime, IoT Core, MQTT, WebSocket, protocol, channel, defineChannel, Channel, parsePayload, RealtimePayloadError, toTopic, toSubscriptionFilter, parseTopic, isTopicSafeId, broadcastGroup, topic layout, scope, group, Standard Schema, valibot, validation, payload
|
|
4
|
+
|
|
5
|
+
> This documentation is published inside the installed package and matches the installed version. Prefer it over prior knowledge or older examples found online.
|
|
6
|
+
|
|
7
|
+
> Full source and examples: https://github.com/BeeSolve/packages/tree/main/packages/realtime-core
|
|
8
|
+
|
|
9
|
+
## How-To Guides
|
|
10
|
+
|
|
11
|
+
| Guide | Description |
|
|
12
|
+
| ------------------------------------------------------------------- | ------------------------------------------------- |
|
|
13
|
+
| [Channels and Validation](./docs/how-to/channels-and-validation.md) | Define channels, topic layout, payload validation |
|
|
14
|
+
|
|
15
|
+
## Further Reading
|
|
16
|
+
|
|
17
|
+
- [README](./README.md) - API reference
|
|
18
|
+
- [CHANGELOG](./CHANGELOG.md) - Version history
|
|
19
|
+
- [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-core/docs) (GitHub only)
|
package/README.md
CHANGED
|
@@ -1,4 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Realtime Core
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
The wire protocol shared by `@beesolve/realtime-client` and `@beesolve/realtime-server`: channel definitions, topic layout and Standard Schema payload validation.
|
|
4
|
+
|
|
5
|
+
> [!WARNING]
|
|
6
|
+
> **Pre-1.0 - unstable API.** This package is `0.x` and under active
|
|
7
|
+
> development. Breaking changes can land in any `0.x` release without a major
|
|
8
|
+
> version bump. Pin an exact version and review the changelog before upgrading.
|
|
9
|
+
> Once the API stabilizes and the package reaches `1.0.0`, it follows semantic
|
|
10
|
+
> versioning and this notice is removed.
|
|
11
|
+
|
|
12
|
+
## Installation
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
bun add @beesolve/realtime-core
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
(or `npm install @beesolve/realtime-core`)
|
|
19
|
+
|
|
20
|
+
The package has no AWS dependencies and is safe to import in the browser. Its only runtime dependency is the type package `@standard-schema/spec`. Use any Standard Schema library (valibot, zod, arktype) for payloads.
|
|
21
|
+
|
|
22
|
+
## Quick Start
|
|
23
|
+
|
|
24
|
+
Define channels once in a module that both the browser and the server import:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { defineChannel } from "@beesolve/realtime-core";
|
|
28
|
+
import * as v from "valibot";
|
|
29
|
+
|
|
30
|
+
export const orderPaid = defineChannel({
|
|
31
|
+
name: "orders/paid",
|
|
32
|
+
schema: v.object({ orderId: v.string(), amount: v.number() }),
|
|
33
|
+
});
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Publish with `@beesolve/realtime-server/publish` and subscribe with `@beesolve/realtime-client`. Both validate against the same schema.
|
|
37
|
+
|
|
38
|
+
## API
|
|
39
|
+
|
|
40
|
+
| Export | Description |
|
|
41
|
+
| ------------------------------------------ | ---------------------------------------------------------------------------------------------- |
|
|
42
|
+
| `defineChannel({ name, schema })` | Returns a `Channel`. Throws unless the name is 1-6 levels of `[A-Za-z0-9_-]` separated by `/`. |
|
|
43
|
+
| `Channel<TName, TSchema>` | `{ name, schema }`. |
|
|
44
|
+
| `parsePayload({ schema, value })` | Validates with the schema and returns the output. Throws `RealtimePayloadError`. |
|
|
45
|
+
| `RealtimePayloadError` | Error with an `issues` array of Standard Schema issues. |
|
|
46
|
+
| `toTopic({ scope, group, channel })` | Builds `<scope>/<group>/<channel>`. Throws on unsafe ids or a topic of 256 bytes or more. |
|
|
47
|
+
| `toSubscriptionFilter({ scope, channel })` | Builds `<scope>/+/<channel>`, which matches every group of a channel. |
|
|
48
|
+
| `parseTopic({ scope, topic })` | Returns `{ group, channel }`, or `null` for a foreign scope or malformed topic. |
|
|
49
|
+
| `isTopicSafeId(value)` | True for `[A-Za-z0-9_-]{1,128}`. Used for scope, user ids and group ids. |
|
|
50
|
+
| `broadcastGroup` | `"__all__"`, the group every connected client receives. |
|
|
51
|
+
|
|
52
|
+
## Cost
|
|
53
|
+
|
|
54
|
+
The infrastructure behind these packages is billed by AWS IoT Core, CloudFront, Lambda and DynamoDB. See the [Cost section of `@beesolve/realtime-server`](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server#cost).
|
|
55
|
+
|
|
56
|
+
## Further Reading
|
|
57
|
+
|
|
58
|
+
- [DOCS.md](./DOCS.md) - Agent-oriented index
|
|
59
|
+
- [Architecture Decision Records](https://github.com/BeeSolve/packages/tree/main/packages/realtime-core/docs) (GitHub only)
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
2
|
+
/** Group id that every connected client receives. */
|
|
3
|
+
declare const broadcastGroup: "__all__";
|
|
4
|
+
/** A named realtime channel with the schema its payloads must satisfy. */
|
|
5
|
+
interface Channel<
|
|
6
|
+
TName extends string,
|
|
7
|
+
TSchema extends StandardSchemaV1
|
|
8
|
+
> {
|
|
9
|
+
readonly name: TName;
|
|
10
|
+
readonly schema: TSchema;
|
|
11
|
+
}
|
|
12
|
+
/** Thrown by `parsePayload` when a payload does not satisfy the channel schema. */
|
|
13
|
+
declare class RealtimePayloadError extends Error {
|
|
14
|
+
readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
|
|
15
|
+
constructor(issues: ReadonlyArray<StandardSchemaV1.Issue>);
|
|
16
|
+
}
|
|
17
|
+
/** Throws when the name is not 1-6 levels of [A-Za-z0-9_-] separated by "/". */
|
|
18
|
+
declare function defineChannel<
|
|
19
|
+
TName extends string,
|
|
20
|
+
TSchema extends StandardSchemaV1
|
|
21
|
+
>(props: {
|
|
22
|
+
readonly name: TName;
|
|
23
|
+
readonly schema: TSchema;
|
|
24
|
+
}): Channel<TName, TSchema>;
|
|
25
|
+
/** Validates with `schema["~standard"].validate`, throws `RealtimePayloadError` listing issues. */
|
|
26
|
+
declare function parsePayload<TSchema extends StandardSchemaV1>(props: {
|
|
27
|
+
readonly schema: TSchema;
|
|
28
|
+
readonly value: unknown;
|
|
29
|
+
}): Promise<StandardSchemaV1.InferOutput<TSchema>>;
|
|
30
|
+
/** [A-Za-z0-9_-]{1,128}. Used for scope, userId and group ids. */
|
|
31
|
+
declare function isTopicSafeId(value: string): boolean;
|
|
32
|
+
/** Builds `<scope>/<group>/<channel>`. Throws on unsafe ids, invalid channel or topics of 256 bytes or more. */
|
|
33
|
+
declare function toTopic(props: {
|
|
34
|
+
readonly scope: string;
|
|
35
|
+
readonly group: string;
|
|
36
|
+
readonly channel: string;
|
|
37
|
+
}): string;
|
|
38
|
+
/** Builds the `<scope>/+/<channel>` filter that matches every group of a channel. */
|
|
39
|
+
declare function toSubscriptionFilter(props: {
|
|
40
|
+
readonly scope: string;
|
|
41
|
+
readonly channel: string;
|
|
42
|
+
}): string;
|
|
43
|
+
/** Splits a topic into group and channel. Returns null for a foreign scope or a malformed topic. */
|
|
44
|
+
declare function parseTopic(props: {
|
|
45
|
+
readonly scope: string;
|
|
46
|
+
readonly topic: string;
|
|
47
|
+
}): {
|
|
48
|
+
group: string;
|
|
49
|
+
channel: string;
|
|
50
|
+
} | null;
|
|
51
|
+
export { Channel, RealtimePayloadError, broadcastGroup, defineChannel, isTopicSafeId, parsePayload, parseTopic, toSubscriptionFilter, toTopic };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// packages/realtime-core/index.ts
|
|
2
|
+
var broadcastGroup = "__all__";
|
|
3
|
+
|
|
4
|
+
class RealtimePayloadError extends Error {
|
|
5
|
+
issues;
|
|
6
|
+
constructor(issues) {
|
|
7
|
+
super(`Invalid realtime payload: ${issues.map((issue) => issue.message).join("; ")}`);
|
|
8
|
+
this.name = "RealtimePayloadError";
|
|
9
|
+
this.issues = issues;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function defineChannel(props) {
|
|
13
|
+
assertChannelName(props.name);
|
|
14
|
+
return { name: props.name, schema: props.schema };
|
|
15
|
+
}
|
|
16
|
+
async function parsePayload(props) {
|
|
17
|
+
const result = await props.schema["~standard"].validate(props.value);
|
|
18
|
+
if (result.issues != null) {
|
|
19
|
+
throw new RealtimePayloadError(result.issues);
|
|
20
|
+
}
|
|
21
|
+
return result.value;
|
|
22
|
+
}
|
|
23
|
+
function isTopicSafeId(value) {
|
|
24
|
+
return topicSafeIdPattern.test(value);
|
|
25
|
+
}
|
|
26
|
+
function toTopic(props) {
|
|
27
|
+
assertTopicSafeId({ label: "scope", value: props.scope });
|
|
28
|
+
assertTopicSafeId({ label: "group", value: props.group });
|
|
29
|
+
assertChannelName(props.channel);
|
|
30
|
+
const topic = `${props.scope}/${props.group}/${props.channel}`;
|
|
31
|
+
assertTopicLength(topic);
|
|
32
|
+
return topic;
|
|
33
|
+
}
|
|
34
|
+
function toSubscriptionFilter(props) {
|
|
35
|
+
assertTopicSafeId({ label: "scope", value: props.scope });
|
|
36
|
+
assertChannelName(props.channel);
|
|
37
|
+
const filter = `${props.scope}/+/${props.channel}`;
|
|
38
|
+
assertTopicLength(filter);
|
|
39
|
+
return filter;
|
|
40
|
+
}
|
|
41
|
+
function parseTopic(props) {
|
|
42
|
+
if (!isTopicSafeId(props.scope))
|
|
43
|
+
return null;
|
|
44
|
+
const prefix = `${props.scope}/`;
|
|
45
|
+
if (!props.topic.startsWith(prefix))
|
|
46
|
+
return null;
|
|
47
|
+
const rest = props.topic.slice(prefix.length);
|
|
48
|
+
const separator = rest.indexOf("/");
|
|
49
|
+
if (separator === -1)
|
|
50
|
+
return null;
|
|
51
|
+
const group = rest.slice(0, separator);
|
|
52
|
+
const channel = rest.slice(separator + 1);
|
|
53
|
+
if (!isTopicSafeId(group))
|
|
54
|
+
return null;
|
|
55
|
+
if (!channelNamePattern.test(channel))
|
|
56
|
+
return null;
|
|
57
|
+
return { group, channel };
|
|
58
|
+
}
|
|
59
|
+
var topicSafeIdPattern = /^[A-Za-z0-9_-]{1,128}$/;
|
|
60
|
+
var channelNamePattern = /^[A-Za-z0-9_-]+(\/[A-Za-z0-9_-]+){0,5}$/;
|
|
61
|
+
var maxTopicBytes = 256;
|
|
62
|
+
function assertChannelName(name) {
|
|
63
|
+
if (!channelNamePattern.test(name)) {
|
|
64
|
+
throw new Error(`Invalid channel name "${name}": expected 1-6 levels of [A-Za-z0-9_-] separated by "/"`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
function assertTopicSafeId(props) {
|
|
68
|
+
if (!isTopicSafeId(props.value)) {
|
|
69
|
+
throw new Error(`Invalid ${props.label} "${props.value}": expected [A-Za-z0-9_-]{1,128}`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function assertTopicLength(topic) {
|
|
73
|
+
if (new TextEncoder().encode(topic).length >= maxTopicBytes) {
|
|
74
|
+
throw new Error(`Topic is ${maxTopicBytes} bytes or longer: "${topic}"`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
export {
|
|
78
|
+
RealtimePayloadError,
|
|
79
|
+
broadcastGroup,
|
|
80
|
+
defineChannel,
|
|
81
|
+
isTopicSafeId,
|
|
82
|
+
parsePayload,
|
|
83
|
+
parseTopic,
|
|
84
|
+
toSubscriptionFilter,
|
|
85
|
+
toTopic
|
|
86
|
+
};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# How to: Define Channels and Validate Payloads
|
|
2
|
+
|
|
3
|
+
## Prerequisites
|
|
4
|
+
|
|
5
|
+
- A Standard Schema library such as valibot
|
|
6
|
+
|
|
7
|
+
## Steps
|
|
8
|
+
|
|
9
|
+
### 1. Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
bun add @beesolve/realtime-core valibot
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
### 2. Define a channel in a shared module
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { defineChannel } from "@beesolve/realtime-core";
|
|
19
|
+
import * as v from "valibot";
|
|
20
|
+
|
|
21
|
+
export const maintenance = defineChannel({
|
|
22
|
+
name: "system/maintenance",
|
|
23
|
+
schema: v.object({ startsAt: v.string(), minutes: v.number() }),
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
A channel name has 1 to 6 levels of `[A-Za-z0-9_-]` separated by `/`. `defineChannel` throws on anything else, so a bad name fails at module load.
|
|
28
|
+
|
|
29
|
+
### 3. Know the topic layout
|
|
30
|
+
|
|
31
|
+
Every message travels on `<scope>/<group>/<channel>`:
|
|
32
|
+
|
|
33
|
+
- `scope` is one prefix per app and stage, for example `myapp-dev`.
|
|
34
|
+
- `group` is a user id, a custom group id, or `broadcastGroup` (`"__all__"`).
|
|
35
|
+
- `channel` is the channel name, which may contain `/`.
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { parseTopic, toSubscriptionFilter, toTopic } from "@beesolve/realtime-core";
|
|
39
|
+
|
|
40
|
+
toTopic({ scope: "myapp-dev", group: "u1", channel: "orders/paid" });
|
|
41
|
+
// "myapp-dev/u1/orders/paid"
|
|
42
|
+
toSubscriptionFilter({ scope: "myapp-dev", channel: "orders/paid" });
|
|
43
|
+
// "myapp-dev/+/orders/paid"
|
|
44
|
+
parseTopic({ scope: "myapp-dev", topic: "myapp-dev/u1/orders/paid" });
|
|
45
|
+
// { group: "u1", channel: "orders/paid" }
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The client subscribes to the `+` filter. The server policy decides which groups the connection may receive, so the client never needs to know its user id.
|
|
49
|
+
|
|
50
|
+
### 4. Validate a payload
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { RealtimePayloadError, parsePayload } from "@beesolve/realtime-core";
|
|
54
|
+
|
|
55
|
+
try {
|
|
56
|
+
const payload = await parsePayload({ schema: maintenance.schema, value: input });
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (error instanceof RealtimePayloadError) console.log(error.issues);
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
The publisher and the client call `parsePayload` for you. Payloads are JSON, so schemas should describe JSON values (strings for dates).
|
|
63
|
+
|
|
64
|
+
## Common Pitfalls
|
|
65
|
+
|
|
66
|
+
- Ids (scope, user id, group) must match `[A-Za-z0-9_-]{1,128}`. `toTopic` throws otherwise.
|
|
67
|
+
- A topic must stay under 256 bytes. Keep channel names short.
|
|
68
|
+
- Changing the topic layout is a wire-protocol change. Upgrade client and server packages together.
|
|
69
|
+
|
|
70
|
+
## See Also
|
|
71
|
+
|
|
72
|
+
- [@beesolve/realtime-server](https://github.com/BeeSolve/packages/tree/main/packages/realtime-server)
|
|
73
|
+
- [@beesolve/realtime-client](https://github.com/BeeSolve/packages/tree/main/packages/realtime-client)
|
package/package.json
CHANGED
|
@@ -1,14 +1,34 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@beesolve/realtime-core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Placeholder package to reserve the npm name and configure OIDC Trusted Publisher.",
|
|
3
|
+
"version": "0.1.0",
|
|
5
4
|
"license": "MIT",
|
|
6
5
|
"repository": {
|
|
7
6
|
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/BeeSolve/packages.git"
|
|
9
|
-
"directory": "packages/realtime-core"
|
|
7
|
+
"url": "git+https://github.com/BeeSolve/packages.git"
|
|
10
8
|
},
|
|
11
|
-
"
|
|
12
|
-
"
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"docs/how-to",
|
|
12
|
+
"DOCS.md"
|
|
13
|
+
],
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"import": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"type-check": "tsc --noEmit"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@standard-schema/spec": "^1.1.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"valibot": "^1.5.0"
|
|
13
33
|
}
|
|
14
34
|
}
|