popsub 0.0.0-stage → 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/LICENSE +201 -0
- package/README.md +196 -2
- package/dist/admin.d.ts +175 -0
- package/dist/admin.js +257 -0
- package/dist/admin.js.map +1 -0
- package/dist/backoff.d.ts +32 -0
- package/dist/backoff.js +31 -0
- package/dist/backoff.js.map +1 -0
- package/dist/base64.d.ts +24 -0
- package/dist/base64.js +104 -0
- package/dist/base64.js.map +1 -0
- package/dist/client.d.ts +250 -0
- package/dist/client.js +322 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +117 -0
- package/dist/config.js +116 -0
- package/dist/config.js.map +1 -0
- package/dist/dedup.d.ts +107 -0
- package/dist/dedup.js +150 -0
- package/dist/dedup.js.map +1 -0
- package/dist/engine.d.ts +224 -0
- package/dist/engine.js +1306 -0
- package/dist/engine.js.map +1 -0
- package/dist/errors.d.ts +80 -0
- package/dist/errors.js +90 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +111 -0
- package/dist/events.js +57 -0
- package/dist/events.js.map +1 -0
- package/dist/handshake.d.ts +91 -0
- package/dist/handshake.js +266 -0
- package/dist/handshake.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/pattern.d.ts +24 -0
- package/dist/pattern.js +43 -0
- package/dist/pattern.js.map +1 -0
- package/dist/protocol.d.ts +313 -0
- package/dist/protocol.js +173 -0
- package/dist/protocol.js.map +1 -0
- package/dist/subscription.d.ts +187 -0
- package/dist/subscription.js +268 -0
- package/dist/subscription.js.map +1 -0
- package/package.json +50 -4
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Client`, the handle the application holds.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { Admin } from "./admin.js";
|
|
7
|
+
import { type ClientConfig } from "./config.js";
|
|
8
|
+
import { type Published } from "./engine.js";
|
|
9
|
+
import type { ClientEventListener } from "./events.js";
|
|
10
|
+
import type { CloseCode, WireStartFrom } from "./protocol.js";
|
|
11
|
+
import type { Subscription } from "./subscription.js";
|
|
12
|
+
/**
|
|
13
|
+
* Where replay starts when subscribing.
|
|
14
|
+
*
|
|
15
|
+
* - `"resume"`: one past a durable session's stored cursor for the topic;
|
|
16
|
+
* for an ephemeral connection, or a topic the session has no cursor for,
|
|
17
|
+
* the same as `"new"`.
|
|
18
|
+
* - `"new"`: only messages published from now on.
|
|
19
|
+
* - `{ last: n }`: the last `n` retained messages.
|
|
20
|
+
* - `{ sinceMs: t }`: retained messages published at or after `t`
|
|
21
|
+
* (milliseconds since the Unix epoch).
|
|
22
|
+
* - `{ seq: s }`: retained messages from `seq` `s` on.
|
|
23
|
+
*/
|
|
24
|
+
export type StartFrom = "resume" | "new" | {
|
|
25
|
+
last: number;
|
|
26
|
+
} | {
|
|
27
|
+
sinceMs: number;
|
|
28
|
+
} | {
|
|
29
|
+
seq: number;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Converts a start position to its wire form.
|
|
33
|
+
*
|
|
34
|
+
* @param from - The start position.
|
|
35
|
+
* @returns The wire form.
|
|
36
|
+
* @throws PopSubError of kind `config` when it is none of the allowed shapes.
|
|
37
|
+
*/
|
|
38
|
+
export declare function startFromToWire(from: StartFrom): WireStartFrom;
|
|
39
|
+
/**
|
|
40
|
+
* Waits for a promise for at most a given time.
|
|
41
|
+
*
|
|
42
|
+
* @param promise - What to wait for.
|
|
43
|
+
* @param ms - The limit in milliseconds.
|
|
44
|
+
* @returns The promise's value.
|
|
45
|
+
* @throws PopSubError of kind `timeout` when the limit passes first, or
|
|
46
|
+
* whatever the promise rejects with.
|
|
47
|
+
*/
|
|
48
|
+
export declare function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T>;
|
|
49
|
+
/**
|
|
50
|
+
* A connection to a PopSub server that reconnects on its own, resubscribes
|
|
51
|
+
* without gaps, resends confirmed publishes without duplicating them,
|
|
52
|
+
* acknowledges QoS 1 messages and hands each `(topic, seq)` to the
|
|
53
|
+
* application once.
|
|
54
|
+
*
|
|
55
|
+
* Create one with `Client.connect`. It runs until `close` is called or the
|
|
56
|
+
* server stops it in a way that rules out reconnecting.
|
|
57
|
+
*/
|
|
58
|
+
export declare class Client {
|
|
59
|
+
#private;
|
|
60
|
+
/**
|
|
61
|
+
* Wraps a running engine. Use `Client.connect` instead.
|
|
62
|
+
*
|
|
63
|
+
* @param engine - The engine.
|
|
64
|
+
* @param config - The configuration.
|
|
65
|
+
*/
|
|
66
|
+
private constructor();
|
|
67
|
+
/**
|
|
68
|
+
* Connects to a server and starts the client.
|
|
69
|
+
*
|
|
70
|
+
* Waits for the first connection to log in and authenticate, retrying
|
|
71
|
+
* with the reconnect policy, for up to `requestTimeoutMs`.
|
|
72
|
+
*
|
|
73
|
+
* @param config - Where and how to connect.
|
|
74
|
+
* @param listener - Called with every event, starting with the first
|
|
75
|
+
* `connected`; more can be added with `on`.
|
|
76
|
+
* @returns The connected client.
|
|
77
|
+
* @throws PopSubError of kind `config` for an invalid configuration;
|
|
78
|
+
* `server` when the server refused the credentials (`invalid_credentials`),
|
|
79
|
+
* the protocol version or the session id; `closed` when the server
|
|
80
|
+
* closed the connection in a way that rules out retrying; `timeout`
|
|
81
|
+
* when no connection succeeded in time; `connect` when the reconnect
|
|
82
|
+
* policy ran out of attempts.
|
|
83
|
+
*/
|
|
84
|
+
static connect(config: ClientConfig, listener?: ClientEventListener): Promise<Client>;
|
|
85
|
+
/**
|
|
86
|
+
* Subscribes to a topic, or to every topic matching a wildcard pattern.
|
|
87
|
+
* Subscribing again to the same topic or pattern replaces the earlier
|
|
88
|
+
* subscription, which ends. A topic subscribed again starts over from
|
|
89
|
+
* `from`. A pattern subscribed again keeps the topics it had joined:
|
|
90
|
+
* their later messages go to the new subscription, each once, and the
|
|
91
|
+
* earlier subscription can be closed or dropped without losing any.
|
|
92
|
+
*
|
|
93
|
+
* With a durable session started in an earlier process, the server sends
|
|
94
|
+
* what it kept for the session's topics as soon as the client connects.
|
|
95
|
+
* The client neither hands over nor acknowledges those messages until
|
|
96
|
+
* the application subscribes to the topic, by name or through a pattern
|
|
97
|
+
* that matches it; the subscribe then replays them in order. Messages of
|
|
98
|
+
* a topic the application never subscribes to stay on the server.
|
|
99
|
+
*
|
|
100
|
+
* In a pattern a whole level may be `+` (any one level) and the last
|
|
101
|
+
* level may be `#` (the rest), as in `sensors/+/temp` or `orders/#`. The
|
|
102
|
+
* one subscription then yields the messages of every matching topic the
|
|
103
|
+
* user may read, including topics created later, each under its own
|
|
104
|
+
* `topic` and `seq`. Order is kept within each topic, not across topics.
|
|
105
|
+
* When the server ends one of those topics (an `unsubscribed` event),
|
|
106
|
+
* only that topic stops.
|
|
107
|
+
*
|
|
108
|
+
* @param topic - The topic or pattern.
|
|
109
|
+
* @param from - Where replay starts; `"resume"` by default. For a
|
|
110
|
+
* pattern it applies to each topic that exists when subscribing.
|
|
111
|
+
* @returns The subscription, which yields each topic's messages in `seq` order.
|
|
112
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
113
|
+
* example `not_authorized` or `invalid_topic`), `timeout` when it
|
|
114
|
+
* didn't complete in time, `closed` when the client has stopped, or
|
|
115
|
+
* `config` for an invalid `from`.
|
|
116
|
+
*/
|
|
117
|
+
subscribe(topic: string, from?: StartFrom): Promise<Subscription>;
|
|
118
|
+
/**
|
|
119
|
+
* Joins a shared subscription: each message on the topic goes to one
|
|
120
|
+
* member of the group, so several clients split the work. This client
|
|
121
|
+
* gets only its share, not in strict `seq` order, and a message can
|
|
122
|
+
* reach a second member after the first disconnects without
|
|
123
|
+
* acknowledging it. Duplicates are dropped by remembering the last 4096
|
|
124
|
+
* `seq`s delivered. After a reconnect the client rejoins the group with
|
|
125
|
+
* `resume`; the group's position is kept by the server.
|
|
126
|
+
*
|
|
127
|
+
* @param topic - The topic; a pattern is refused with `bad_request`.
|
|
128
|
+
* @param group - The group: 1 to 64 letters, digits, `_`, `.` or `-`.
|
|
129
|
+
* @param from - Where the group starts the first time it is used on the
|
|
130
|
+
* topic; `"resume"` (which then means `"new"`) by default. Ignored
|
|
131
|
+
* when the group already has a position.
|
|
132
|
+
* @returns The subscription.
|
|
133
|
+
* @throws PopSubError of kind `server` when the server refused it,
|
|
134
|
+
* `timeout`, `closed`, or `config` for an invalid `from`.
|
|
135
|
+
*/
|
|
136
|
+
subscribeShared(topic: string, group: string, from?: StartFrom): Promise<Subscription>;
|
|
137
|
+
/**
|
|
138
|
+
* Unsubscribes from a topic, or from a pattern and every topic joined
|
|
139
|
+
* through it. Its subscription ends, and a durable session forgets the
|
|
140
|
+
* stored subscription too. While disconnected the unsubscribe
|
|
141
|
+
* is queued and the call succeeds at once.
|
|
142
|
+
*
|
|
143
|
+
* @param topic - The topic or pattern, as it was subscribed.
|
|
144
|
+
* @throws PopSubError of kind `server` when the session store couldn't
|
|
145
|
+
* be updated, `timeout`, or `closed`.
|
|
146
|
+
*/
|
|
147
|
+
unsubscribe(topic: string): Promise<void>;
|
|
148
|
+
/**
|
|
149
|
+
* Publishes a message at QoS 0: sent once, with no confirmation.
|
|
150
|
+
*
|
|
151
|
+
* While disconnected, up to 10,000 such publishes (and queued
|
|
152
|
+
* unsubscribes) are held and sent after reconnecting; beyond that the
|
|
153
|
+
* oldest are dropped. Failures the server reports arrive as
|
|
154
|
+
* `serverError` events.
|
|
155
|
+
*
|
|
156
|
+
* @param topic - The topic.
|
|
157
|
+
* @param payload - The body.
|
|
158
|
+
* @throws PopSubError of kind `closed` when the client has stopped.
|
|
159
|
+
*/
|
|
160
|
+
publish(topic: string, payload: string): void;
|
|
161
|
+
/**
|
|
162
|
+
* Publishes bytes at QoS 0, for a body that isn't text. They travel as
|
|
163
|
+
* standard padded base64 in `payload` with `encoding: "base64"`, so they
|
|
164
|
+
* take about a third more room against the server's payload limit;
|
|
165
|
+
* subscribers read them back with `Message.bytes`.
|
|
166
|
+
*
|
|
167
|
+
* Otherwise it behaves like `publish`, queue while disconnected included.
|
|
168
|
+
*
|
|
169
|
+
* @param topic - The topic.
|
|
170
|
+
* @param bytes - The body.
|
|
171
|
+
* @throws PopSubError of kind `closed` when the client has stopped.
|
|
172
|
+
*/
|
|
173
|
+
publishBytes(topic: string, bytes: Uint8Array): void;
|
|
174
|
+
/**
|
|
175
|
+
* Publishes a message at QoS 1 and waits until the server has stored it.
|
|
176
|
+
*
|
|
177
|
+
* The message gets a new `message_id` (a UUID) and is resent under it,
|
|
178
|
+
* with the same request id, after every reconnect until it is confirmed,
|
|
179
|
+
* so the server stores it once.
|
|
180
|
+
*
|
|
181
|
+
* @param topic - The topic.
|
|
182
|
+
* @param payload - The body.
|
|
183
|
+
* @returns Its `seq` and `messageId`.
|
|
184
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
185
|
+
* example `not_authorized`, `rate_limited` or `payload_too_large`),
|
|
186
|
+
* `timeout` when it wasn't confirmed in time (it may still be stored,
|
|
187
|
+
* and is still resent until confirmed), or `closed`.
|
|
188
|
+
*/
|
|
189
|
+
publishConfirmed(topic: string, payload: string): Promise<Published>;
|
|
190
|
+
/**
|
|
191
|
+
* Publishes bytes at QoS 1 and waits until the server has stored them,
|
|
192
|
+
* for a body that isn't text. They travel as standard padded base64 in
|
|
193
|
+
* `payload` with `encoding: "base64"`, so they take about a third more
|
|
194
|
+
* room against the server's payload limit; subscribers read them back
|
|
195
|
+
* with `Message.bytes`.
|
|
196
|
+
*
|
|
197
|
+
* Otherwise it behaves like `publishConfirmed`: one `message_id`, resent
|
|
198
|
+
* with the same request id after every reconnect until confirmed.
|
|
199
|
+
*
|
|
200
|
+
* @param topic - The topic.
|
|
201
|
+
* @param bytes - The body.
|
|
202
|
+
* @returns Its `seq` and `messageId`.
|
|
203
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
204
|
+
* example `not_authorized`, `rate_limited` or `payload_too_large`),
|
|
205
|
+
* `timeout` when it wasn't confirmed in time (it may still be stored,
|
|
206
|
+
* and is still resent until confirmed), or `closed`.
|
|
207
|
+
*/
|
|
208
|
+
publishBytesConfirmed(topic: string, bytes: Uint8Array): Promise<Published>;
|
|
209
|
+
/**
|
|
210
|
+
* The admin requests: creating accounts, granting and revoking topics,
|
|
211
|
+
* disabling and deleting accounts. They need the client to be logged in
|
|
212
|
+
* as an admin, and are never queued or resent.
|
|
213
|
+
*
|
|
214
|
+
* @returns A handle that sends them through this client.
|
|
215
|
+
*/
|
|
216
|
+
admin(): Admin;
|
|
217
|
+
/**
|
|
218
|
+
* Registers a listener for the client's events: connects, disconnects,
|
|
219
|
+
* truncations, stalls, token refreshes, subscriptions the server ended,
|
|
220
|
+
* and server errors that answer no request.
|
|
221
|
+
*
|
|
222
|
+
* @param listener - Called with every event from now on.
|
|
223
|
+
* @returns A function that removes the listener.
|
|
224
|
+
*/
|
|
225
|
+
on(listener: ClientEventListener): () => void;
|
|
226
|
+
/**
|
|
227
|
+
* Removes a listener registered with `on` or `Client.connect`.
|
|
228
|
+
*
|
|
229
|
+
* @param listener - The listener.
|
|
230
|
+
*/
|
|
231
|
+
off(listener: ClientEventListener): void;
|
|
232
|
+
/**
|
|
233
|
+
* Closes the connection and stops the client. Pending requests fail with
|
|
234
|
+
* a `closed` error, every subscription ends, and no timer or socket is
|
|
235
|
+
* left running.
|
|
236
|
+
*
|
|
237
|
+
* @returns A promise that settles once the client has stopped.
|
|
238
|
+
*/
|
|
239
|
+
close(): Promise<void>;
|
|
240
|
+
/**
|
|
241
|
+
* Why the client stopped, if it has.
|
|
242
|
+
*
|
|
243
|
+
* @returns `{ code }` once stopped, where `code` is the close code that
|
|
244
|
+
* stopped it or `null` when the application closed it or it ran out of
|
|
245
|
+
* attempts; `null` while running.
|
|
246
|
+
*/
|
|
247
|
+
get stopped(): {
|
|
248
|
+
code: CloseCode | null;
|
|
249
|
+
} | null;
|
|
250
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `Client`, the handle the application holds.
|
|
3
|
+
*
|
|
4
|
+
* @module
|
|
5
|
+
*/
|
|
6
|
+
import { Admin } from "./admin.js";
|
|
7
|
+
import { encodeBase64 } from "./base64.js";
|
|
8
|
+
import { resolveConfig } from "./config.js";
|
|
9
|
+
import { Engine } from "./engine.js";
|
|
10
|
+
import { PopSubError } from "./errors.js";
|
|
11
|
+
/**
|
|
12
|
+
* Converts a start position to its wire form.
|
|
13
|
+
*
|
|
14
|
+
* @param from - The start position.
|
|
15
|
+
* @returns The wire form.
|
|
16
|
+
* @throws PopSubError of kind `config` when it is none of the allowed shapes.
|
|
17
|
+
*/
|
|
18
|
+
export function startFromToWire(from) {
|
|
19
|
+
if (from === "resume" || from === "new") {
|
|
20
|
+
return from;
|
|
21
|
+
}
|
|
22
|
+
if (typeof from === "object") {
|
|
23
|
+
if ("last" in from && Number.isInteger(from.last) && from.last >= 0) {
|
|
24
|
+
return { last: from.last };
|
|
25
|
+
}
|
|
26
|
+
if ("sinceMs" in from && Number.isInteger(from.sinceMs)) {
|
|
27
|
+
return { since_ms: from.sinceMs };
|
|
28
|
+
}
|
|
29
|
+
if ("seq" in from && Number.isInteger(from.seq) && from.seq >= 0) {
|
|
30
|
+
return { seq: from.seq };
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw new PopSubError("config", "from must be resume, new, { last }, { sinceMs } or { seq }");
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Waits for a promise for at most a given time.
|
|
37
|
+
*
|
|
38
|
+
* @param promise - What to wait for.
|
|
39
|
+
* @param ms - The limit in milliseconds.
|
|
40
|
+
* @returns The promise's value.
|
|
41
|
+
* @throws PopSubError of kind `timeout` when the limit passes first, or
|
|
42
|
+
* whatever the promise rejects with.
|
|
43
|
+
*/
|
|
44
|
+
export function withTimeout(promise, ms) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
reject(PopSubError.timeout());
|
|
48
|
+
}, ms);
|
|
49
|
+
promise.then((value) => {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
resolve(value);
|
|
52
|
+
}, (error) => {
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* A connection to a PopSub server that reconnects on its own, resubscribes
|
|
60
|
+
* without gaps, resends confirmed publishes without duplicating them,
|
|
61
|
+
* acknowledges QoS 1 messages and hands each `(topic, seq)` to the
|
|
62
|
+
* application once.
|
|
63
|
+
*
|
|
64
|
+
* Create one with `Client.connect`. It runs until `close` is called or the
|
|
65
|
+
* server stops it in a way that rules out reconnecting.
|
|
66
|
+
*/
|
|
67
|
+
export class Client {
|
|
68
|
+
/** The engine that owns the connection. */
|
|
69
|
+
#engine;
|
|
70
|
+
/** The configuration, for the request timeout. */
|
|
71
|
+
#config;
|
|
72
|
+
/**
|
|
73
|
+
* Wraps a running engine. Use `Client.connect` instead.
|
|
74
|
+
*
|
|
75
|
+
* @param engine - The engine.
|
|
76
|
+
* @param config - The configuration.
|
|
77
|
+
*/
|
|
78
|
+
constructor(engine, config) {
|
|
79
|
+
this.#engine = engine;
|
|
80
|
+
this.#config = config;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Connects to a server and starts the client.
|
|
84
|
+
*
|
|
85
|
+
* Waits for the first connection to log in and authenticate, retrying
|
|
86
|
+
* with the reconnect policy, for up to `requestTimeoutMs`.
|
|
87
|
+
*
|
|
88
|
+
* @param config - Where and how to connect.
|
|
89
|
+
* @param listener - Called with every event, starting with the first
|
|
90
|
+
* `connected`; more can be added with `on`.
|
|
91
|
+
* @returns The connected client.
|
|
92
|
+
* @throws PopSubError of kind `config` for an invalid configuration;
|
|
93
|
+
* `server` when the server refused the credentials (`invalid_credentials`),
|
|
94
|
+
* the protocol version or the session id; `closed` when the server
|
|
95
|
+
* closed the connection in a way that rules out retrying; `timeout`
|
|
96
|
+
* when no connection succeeded in time; `connect` when the reconnect
|
|
97
|
+
* policy ran out of attempts.
|
|
98
|
+
*/
|
|
99
|
+
static async connect(config, listener) {
|
|
100
|
+
const resolved = resolveConfig(config);
|
|
101
|
+
const engine = new Engine(resolved);
|
|
102
|
+
if (listener !== undefined) {
|
|
103
|
+
engine.emitter.on(listener);
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
await withTimeout(engine.ready, resolved.requestTimeoutMs);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
await engine.close();
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
return new Client(engine, resolved);
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Subscribes to a topic, or to every topic matching a wildcard pattern.
|
|
116
|
+
* Subscribing again to the same topic or pattern replaces the earlier
|
|
117
|
+
* subscription, which ends. A topic subscribed again starts over from
|
|
118
|
+
* `from`. A pattern subscribed again keeps the topics it had joined:
|
|
119
|
+
* their later messages go to the new subscription, each once, and the
|
|
120
|
+
* earlier subscription can be closed or dropped without losing any.
|
|
121
|
+
*
|
|
122
|
+
* With a durable session started in an earlier process, the server sends
|
|
123
|
+
* what it kept for the session's topics as soon as the client connects.
|
|
124
|
+
* The client neither hands over nor acknowledges those messages until
|
|
125
|
+
* the application subscribes to the topic, by name or through a pattern
|
|
126
|
+
* that matches it; the subscribe then replays them in order. Messages of
|
|
127
|
+
* a topic the application never subscribes to stay on the server.
|
|
128
|
+
*
|
|
129
|
+
* In a pattern a whole level may be `+` (any one level) and the last
|
|
130
|
+
* level may be `#` (the rest), as in `sensors/+/temp` or `orders/#`. The
|
|
131
|
+
* one subscription then yields the messages of every matching topic the
|
|
132
|
+
* user may read, including topics created later, each under its own
|
|
133
|
+
* `topic` and `seq`. Order is kept within each topic, not across topics.
|
|
134
|
+
* When the server ends one of those topics (an `unsubscribed` event),
|
|
135
|
+
* only that topic stops.
|
|
136
|
+
*
|
|
137
|
+
* @param topic - The topic or pattern.
|
|
138
|
+
* @param from - Where replay starts; `"resume"` by default. For a
|
|
139
|
+
* pattern it applies to each topic that exists when subscribing.
|
|
140
|
+
* @returns The subscription, which yields each topic's messages in `seq` order.
|
|
141
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
142
|
+
* example `not_authorized` or `invalid_topic`), `timeout` when it
|
|
143
|
+
* didn't complete in time, `closed` when the client has stopped, or
|
|
144
|
+
* `config` for an invalid `from`.
|
|
145
|
+
*/
|
|
146
|
+
subscribe(topic, from = "resume") {
|
|
147
|
+
return this.#subscribe(topic, from, null);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Joins a shared subscription: each message on the topic goes to one
|
|
151
|
+
* member of the group, so several clients split the work. This client
|
|
152
|
+
* gets only its share, not in strict `seq` order, and a message can
|
|
153
|
+
* reach a second member after the first disconnects without
|
|
154
|
+
* acknowledging it. Duplicates are dropped by remembering the last 4096
|
|
155
|
+
* `seq`s delivered. After a reconnect the client rejoins the group with
|
|
156
|
+
* `resume`; the group's position is kept by the server.
|
|
157
|
+
*
|
|
158
|
+
* @param topic - The topic; a pattern is refused with `bad_request`.
|
|
159
|
+
* @param group - The group: 1 to 64 letters, digits, `_`, `.` or `-`.
|
|
160
|
+
* @param from - Where the group starts the first time it is used on the
|
|
161
|
+
* topic; `"resume"` (which then means `"new"`) by default. Ignored
|
|
162
|
+
* when the group already has a position.
|
|
163
|
+
* @returns The subscription.
|
|
164
|
+
* @throws PopSubError of kind `server` when the server refused it,
|
|
165
|
+
* `timeout`, `closed`, or `config` for an invalid `from`.
|
|
166
|
+
*/
|
|
167
|
+
subscribeShared(topic, group, from = "resume") {
|
|
168
|
+
return this.#subscribe(topic, from, group);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Subscribes and waits for the server to confirm it, closing the
|
|
172
|
+
* subscription if it is refused or takes too long.
|
|
173
|
+
*
|
|
174
|
+
* @param topic - The topic or pattern.
|
|
175
|
+
* @param from - Where replay starts.
|
|
176
|
+
* @param group - The shared subscription to join, or `null`.
|
|
177
|
+
* @returns The subscription.
|
|
178
|
+
*/
|
|
179
|
+
async #subscribe(topic, from, group) {
|
|
180
|
+
const { subscription, done } = this.#engine.subscribe(topic, startFromToWire(from), group);
|
|
181
|
+
try {
|
|
182
|
+
await withTimeout(done, this.#config.requestTimeoutMs);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
subscription.close();
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
return subscription;
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Unsubscribes from a topic, or from a pattern and every topic joined
|
|
192
|
+
* through it. Its subscription ends, and a durable session forgets the
|
|
193
|
+
* stored subscription too. While disconnected the unsubscribe
|
|
194
|
+
* is queued and the call succeeds at once.
|
|
195
|
+
*
|
|
196
|
+
* @param topic - The topic or pattern, as it was subscribed.
|
|
197
|
+
* @throws PopSubError of kind `server` when the session store couldn't
|
|
198
|
+
* be updated, `timeout`, or `closed`.
|
|
199
|
+
*/
|
|
200
|
+
async unsubscribe(topic) {
|
|
201
|
+
await withTimeout(this.#engine.unsubscribe(topic), this.#config.requestTimeoutMs);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Publishes a message at QoS 0: sent once, with no confirmation.
|
|
205
|
+
*
|
|
206
|
+
* While disconnected, up to 10,000 such publishes (and queued
|
|
207
|
+
* unsubscribes) are held and sent after reconnecting; beyond that the
|
|
208
|
+
* oldest are dropped. Failures the server reports arrive as
|
|
209
|
+
* `serverError` events.
|
|
210
|
+
*
|
|
211
|
+
* @param topic - The topic.
|
|
212
|
+
* @param payload - The body.
|
|
213
|
+
* @throws PopSubError of kind `closed` when the client has stopped.
|
|
214
|
+
*/
|
|
215
|
+
publish(topic, payload) {
|
|
216
|
+
this.#engine.publish(topic, payload);
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Publishes bytes at QoS 0, for a body that isn't text. They travel as
|
|
220
|
+
* standard padded base64 in `payload` with `encoding: "base64"`, so they
|
|
221
|
+
* take about a third more room against the server's payload limit;
|
|
222
|
+
* subscribers read them back with `Message.bytes`.
|
|
223
|
+
*
|
|
224
|
+
* Otherwise it behaves like `publish`, queue while disconnected included.
|
|
225
|
+
*
|
|
226
|
+
* @param topic - The topic.
|
|
227
|
+
* @param bytes - The body.
|
|
228
|
+
* @throws PopSubError of kind `closed` when the client has stopped.
|
|
229
|
+
*/
|
|
230
|
+
publishBytes(topic, bytes) {
|
|
231
|
+
this.#engine.publish(topic, encodeBase64(bytes), "base64");
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Publishes a message at QoS 1 and waits until the server has stored it.
|
|
235
|
+
*
|
|
236
|
+
* The message gets a new `message_id` (a UUID) and is resent under it,
|
|
237
|
+
* with the same request id, after every reconnect until it is confirmed,
|
|
238
|
+
* so the server stores it once.
|
|
239
|
+
*
|
|
240
|
+
* @param topic - The topic.
|
|
241
|
+
* @param payload - The body.
|
|
242
|
+
* @returns Its `seq` and `messageId`.
|
|
243
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
244
|
+
* example `not_authorized`, `rate_limited` or `payload_too_large`),
|
|
245
|
+
* `timeout` when it wasn't confirmed in time (it may still be stored,
|
|
246
|
+
* and is still resent until confirmed), or `closed`.
|
|
247
|
+
*/
|
|
248
|
+
publishConfirmed(topic, payload) {
|
|
249
|
+
return withTimeout(this.#engine.publishConfirmed(topic, payload), this.#config.requestTimeoutMs);
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Publishes bytes at QoS 1 and waits until the server has stored them,
|
|
253
|
+
* for a body that isn't text. They travel as standard padded base64 in
|
|
254
|
+
* `payload` with `encoding: "base64"`, so they take about a third more
|
|
255
|
+
* room against the server's payload limit; subscribers read them back
|
|
256
|
+
* with `Message.bytes`.
|
|
257
|
+
*
|
|
258
|
+
* Otherwise it behaves like `publishConfirmed`: one `message_id`, resent
|
|
259
|
+
* with the same request id after every reconnect until confirmed.
|
|
260
|
+
*
|
|
261
|
+
* @param topic - The topic.
|
|
262
|
+
* @param bytes - The body.
|
|
263
|
+
* @returns Its `seq` and `messageId`.
|
|
264
|
+
* @throws PopSubError of kind `server` when the server refused it (for
|
|
265
|
+
* example `not_authorized`, `rate_limited` or `payload_too_large`),
|
|
266
|
+
* `timeout` when it wasn't confirmed in time (it may still be stored,
|
|
267
|
+
* and is still resent until confirmed), or `closed`.
|
|
268
|
+
*/
|
|
269
|
+
publishBytesConfirmed(topic, bytes) {
|
|
270
|
+
return withTimeout(this.#engine.publishConfirmed(topic, encodeBase64(bytes), "base64"), this.#config.requestTimeoutMs);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The admin requests: creating accounts, granting and revoking topics,
|
|
274
|
+
* disabling and deleting accounts. They need the client to be logged in
|
|
275
|
+
* as an admin, and are never queued or resent.
|
|
276
|
+
*
|
|
277
|
+
* @returns A handle that sends them through this client.
|
|
278
|
+
*/
|
|
279
|
+
admin() {
|
|
280
|
+
return new Admin((request) => withTimeout(this.#engine.request(request), this.#config.requestTimeoutMs));
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Registers a listener for the client's events: connects, disconnects,
|
|
284
|
+
* truncations, stalls, token refreshes, subscriptions the server ended,
|
|
285
|
+
* and server errors that answer no request.
|
|
286
|
+
*
|
|
287
|
+
* @param listener - Called with every event from now on.
|
|
288
|
+
* @returns A function that removes the listener.
|
|
289
|
+
*/
|
|
290
|
+
on(listener) {
|
|
291
|
+
return this.#engine.emitter.on(listener);
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Removes a listener registered with `on` or `Client.connect`.
|
|
295
|
+
*
|
|
296
|
+
* @param listener - The listener.
|
|
297
|
+
*/
|
|
298
|
+
off(listener) {
|
|
299
|
+
this.#engine.emitter.off(listener);
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Closes the connection and stops the client. Pending requests fail with
|
|
303
|
+
* a `closed` error, every subscription ends, and no timer or socket is
|
|
304
|
+
* left running.
|
|
305
|
+
*
|
|
306
|
+
* @returns A promise that settles once the client has stopped.
|
|
307
|
+
*/
|
|
308
|
+
close() {
|
|
309
|
+
return this.#engine.close();
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Why the client stopped, if it has.
|
|
313
|
+
*
|
|
314
|
+
* @returns `{ code }` once stopped, where `code` is the close code that
|
|
315
|
+
* stopped it or `null` when the application closed it or it ran out of
|
|
316
|
+
* attempts; `null` while running.
|
|
317
|
+
*/
|
|
318
|
+
get stopped() {
|
|
319
|
+
return this.#engine.stopped;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,aAAa,EAA0C,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,MAAM,EAAkB,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAmB1C;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,IAAe;IAC7C,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;QACxC,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC7B,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,CAAC,EAAE,CAAC;YACpE,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AAO,WAAW,CAChB,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,QAAQ,CAAC,EACnE,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAC9B,CAAC;IACJ,CAAC;IAED;;;;;;OAMG;IACH,KAAK;QACH,OAAO,IAAI,KAAK,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAC3G,CAAC;IAED;;;;;;;OAOG;IACH,EAAE,CAAC,QAA6B;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC;IAC3C,CAAC;IAED;;;;OAIG;IACH,GAAG,CAAC,QAA6B;QAC/B,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACrC,CAAC;IAED;;;;;;OAMG;IACH,KAAK;QACH,OAAO,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IAC9B,CAAC;IAED;;;;;;OAMG;IACH,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/**\n * `Client`, the handle the application holds.\n *\n * @module\n */\n\nimport { Admin } from \"./admin.js\";\nimport { encodeBase64 } from \"./base64.js\";\nimport { resolveConfig, type ClientConfig, type ResolvedConfig } from \"./config.js\";\nimport { Engine, type Published } from \"./engine.js\";\nimport { PopSubError } from \"./errors.js\";\nimport type { ClientEventListener } from \"./events.js\";\nimport type { CloseCode, WireStartFrom } from \"./protocol.js\";\nimport type { Subscription } from \"./subscription.js\";\n\n/**\n * Where replay starts when subscribing.\n *\n * - `\"resume\"`: one past a durable session's stored cursor for the topic;\n * for an ephemeral connection, or a topic the session has no cursor for,\n * the same as `\"new\"`.\n * - `\"new\"`: only messages published from now on.\n * - `{ last: n }`: the last `n` retained messages.\n * - `{ sinceMs: t }`: retained messages published at or after `t`\n * (milliseconds since the Unix epoch).\n * - `{ seq: s }`: retained messages from `seq` `s` on.\n */\nexport type StartFrom = \"resume\" | \"new\" | { last: number } | { sinceMs: number } | { seq: number };\n\n/**\n * Converts a start position to its wire form.\n *\n * @param from - The start position.\n * @returns The wire form.\n * @throws PopSubError of kind `config` when it is none of the allowed shapes.\n */\nexport function startFromToWire(from: StartFrom): WireStartFrom {\n if (from === \"resume\" || from === \"new\") {\n return from;\n }\n if (typeof from === \"object\") {\n if (\"last\" in from && Number.isInteger(from.last) && from.last >= 0) {\n return { last: from.last };\n }\n if (\"sinceMs\" in from && Number.isInteger(from.sinceMs)) {\n return { since_ms: from.sinceMs };\n }\n if (\"seq\" in from && Number.isInteger(from.seq) && from.seq >= 0) {\n return { seq: from.seq };\n }\n }\n throw new PopSubError(\"config\", \"from must be resume, new, { last }, { sinceMs } or { seq }\");\n}\n\n/**\n * Waits for a promise for at most a given time.\n *\n * @param promise - What to wait for.\n * @param ms - The limit in milliseconds.\n * @returns The promise's value.\n * @throws PopSubError of kind `timeout` when the limit passes first, or\n * whatever the promise rejects with.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n reject(PopSubError.timeout());\n }, ms);\n promise.then(\n (value) => {\n clearTimeout(timer);\n resolve(value);\n },\n (error: unknown) => {\n clearTimeout(timer);\n reject(error instanceof Error ? error : new Error(String(error)));\n },\n );\n });\n}\n\n/**\n * A connection to a PopSub server that reconnects on its own, resubscribes\n * without gaps, resends confirmed publishes without duplicating them,\n * acknowledges QoS 1 messages and hands each `(topic, seq)` to the\n * application once.\n *\n * Create one with `Client.connect`. It runs until `close` is called or the\n * server stops it in a way that rules out reconnecting.\n */\nexport class Client {\n /** The engine that owns the connection. */\n readonly #engine: Engine;\n /** The configuration, for the request timeout. */\n readonly #config: ResolvedConfig;\n\n /**\n * Wraps a running engine. Use `Client.connect` instead.\n *\n * @param engine - The engine.\n * @param config - The configuration.\n */\n private constructor(engine: Engine, config: ResolvedConfig) {\n this.#engine = engine;\n this.#config = config;\n }\n\n /**\n * Connects to a server and starts the client.\n *\n * Waits for the first connection to log in and authenticate, retrying\n * with the reconnect policy, for up to `requestTimeoutMs`.\n *\n * @param config - Where and how to connect.\n * @param listener - Called with every event, starting with the first\n * `connected`; more can be added with `on`.\n * @returns The connected client.\n * @throws PopSubError of kind `config` for an invalid configuration;\n * `server` when the server refused the credentials (`invalid_credentials`),\n * the protocol version or the session id; `closed` when the server\n * closed the connection in a way that rules out retrying; `timeout`\n * when no connection succeeded in time; `connect` when the reconnect\n * policy ran out of attempts.\n */\n static async connect(config: ClientConfig, listener?: ClientEventListener): Promise<Client> {\n const resolved = resolveConfig(config);\n const engine = new Engine(resolved);\n if (listener !== undefined) {\n engine.emitter.on(listener);\n }\n try {\n await withTimeout(engine.ready, resolved.requestTimeoutMs);\n } catch (error) {\n await engine.close();\n throw error;\n }\n return new Client(engine, resolved);\n }\n\n /**\n * Subscribes to a topic, or to every topic matching a wildcard pattern.\n * Subscribing again to the same topic or pattern replaces the earlier\n * subscription, which ends. A topic subscribed again starts over from\n * `from`. A pattern subscribed again keeps the topics it had joined:\n * their later messages go to the new subscription, each once, and the\n * earlier subscription can be closed or dropped without losing any.\n *\n * With a durable session started in an earlier process, the server sends\n * what it kept for the session's topics as soon as the client connects.\n * The client neither hands over nor acknowledges those messages until\n * the application subscribes to the topic, by name or through a pattern\n * that matches it; the subscribe then replays them in order. Messages of\n * a topic the application never subscribes to stay on the server.\n *\n * In a pattern a whole level may be `+` (any one level) and the last\n * level may be `#` (the rest), as in `sensors/+/temp` or `orders/#`. The\n * one subscription then yields the messages of every matching topic the\n * user may read, including topics created later, each under its own\n * `topic` and `seq`. Order is kept within each topic, not across topics.\n * When the server ends one of those topics (an `unsubscribed` event),\n * only that topic stops.\n *\n * @param topic - The topic or pattern.\n * @param from - Where replay starts; `\"resume\"` by default. For a\n * pattern it applies to each topic that exists when subscribing.\n * @returns The subscription, which yields each topic's messages in `seq` order.\n * @throws PopSubError of kind `server` when the server refused it (for\n * example `not_authorized` or `invalid_topic`), `timeout` when it\n * didn't complete in time, `closed` when the client has stopped, or\n * `config` for an invalid `from`.\n */\n subscribe(topic: string, from: StartFrom = \"resume\"): Promise<Subscription> {\n return this.#subscribe(topic, from, null);\n }\n\n /**\n * Joins a shared subscription: each message on the topic goes to one\n * member of the group, so several clients split the work. This client\n * gets only its share, not in strict `seq` order, and a message can\n * reach a second member after the first disconnects without\n * acknowledging it. Duplicates are dropped by remembering the last 4096\n * `seq`s delivered. After a reconnect the client rejoins the group with\n * `resume`; the group's position is kept by the server.\n *\n * @param topic - The topic; a pattern is refused with `bad_request`.\n * @param group - The group: 1 to 64 letters, digits, `_`, `.` or `-`.\n * @param from - Where the group starts the first time it is used on the\n * topic; `\"resume\"` (which then means `\"new\"`) by default. Ignored\n * when the group already has a position.\n * @returns The subscription.\n * @throws PopSubError of kind `server` when the server refused it,\n * `timeout`, `closed`, or `config` for an invalid `from`.\n */\n subscribeShared(topic: string, group: string, from: StartFrom = \"resume\"): Promise<Subscription> {\n return this.#subscribe(topic, from, group);\n }\n\n /**\n * Subscribes and waits for the server to confirm it, closing the\n * subscription if it is refused or takes too long.\n *\n * @param topic - The topic or pattern.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n * @returns The subscription.\n */\n async #subscribe(topic: string, from: StartFrom, group: string | null): Promise<Subscription> {\n const { subscription, done } = this.#engine.subscribe(topic, startFromToWire(from), group);\n try {\n await withTimeout(done, this.#config.requestTimeoutMs);\n } catch (error) {\n subscription.close();\n throw error;\n }\n return subscription;\n }\n\n /**\n * Unsubscribes from a topic, or from a pattern and every topic joined\n * through it. Its subscription ends, and a durable session forgets the\n * stored subscription too. While disconnected the unsubscribe\n * is queued and the call succeeds at once.\n *\n * @param topic - The topic or pattern, as it was subscribed.\n * @throws PopSubError of kind `server` when the session store couldn't\n * be updated, `timeout`, or `closed`.\n */\n async unsubscribe(topic: string): Promise<void> {\n await withTimeout(this.#engine.unsubscribe(topic), this.#config.requestTimeoutMs);\n }\n\n /**\n * Publishes a message at QoS 0: sent once, with no confirmation.\n *\n * While disconnected, up to 10,000 such publishes (and queued\n * unsubscribes) are held and sent after reconnecting; beyond that the\n * oldest are dropped. Failures the server reports arrive as\n * `serverError` events.\n *\n * @param topic - The topic.\n * @param payload - The body.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n publish(topic: string, payload: string): void {\n this.#engine.publish(topic, payload);\n }\n\n /**\n * Publishes bytes at QoS 0, for a body that isn't text. They travel as\n * standard padded base64 in `payload` with `encoding: \"base64\"`, so they\n * take about a third more room against the server's payload limit;\n * subscribers read them back with `Message.bytes`.\n *\n * Otherwise it behaves like `publish`, queue while disconnected included.\n *\n * @param topic - The topic.\n * @param bytes - The body.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n publishBytes(topic: string, bytes: Uint8Array): void {\n this.#engine.publish(topic, encodeBase64(bytes), \"base64\");\n }\n\n /**\n * Publishes a message at QoS 1 and waits until the server has stored it.\n *\n * The message gets a new `message_id` (a UUID) and is resent under it,\n * with the same request id, after every reconnect until it is confirmed,\n * so the server stores it once.\n *\n * @param topic - The topic.\n * @param payload - The body.\n * @returns Its `seq` and `messageId`.\n * @throws PopSubError of kind `server` when the server refused it (for\n * example `not_authorized`, `rate_limited` or `payload_too_large`),\n * `timeout` when it wasn't confirmed in time (it may still be stored,\n * and is still resent until confirmed), or `closed`.\n */\n publishConfirmed(topic: string, payload: string): Promise<Published> {\n return withTimeout(this.#engine.publishConfirmed(topic, payload), this.#config.requestTimeoutMs);\n }\n\n /**\n * Publishes bytes at QoS 1 and waits until the server has stored them,\n * for a body that isn't text. They travel as standard padded base64 in\n * `payload` with `encoding: \"base64\"`, so they take about a third more\n * room against the server's payload limit; subscribers read them back\n * with `Message.bytes`.\n *\n * Otherwise it behaves like `publishConfirmed`: one `message_id`, resent\n * with the same request id after every reconnect until confirmed.\n *\n * @param topic - The topic.\n * @param bytes - The body.\n * @returns Its `seq` and `messageId`.\n * @throws PopSubError of kind `server` when the server refused it (for\n * example `not_authorized`, `rate_limited` or `payload_too_large`),\n * `timeout` when it wasn't confirmed in time (it may still be stored,\n * and is still resent until confirmed), or `closed`.\n */\n publishBytesConfirmed(topic: string, bytes: Uint8Array): Promise<Published> {\n return withTimeout(\n this.#engine.publishConfirmed(topic, encodeBase64(bytes), \"base64\"),\n this.#config.requestTimeoutMs,\n );\n }\n\n /**\n * The admin requests: creating accounts, granting and revoking topics,\n * disabling and deleting accounts. They need the client to be logged in\n * as an admin, and are never queued or resent.\n *\n * @returns A handle that sends them through this client.\n */\n admin(): Admin {\n return new Admin((request) => withTimeout(this.#engine.request(request), this.#config.requestTimeoutMs));\n }\n\n /**\n * Registers a listener for the client's events: connects, disconnects,\n * truncations, stalls, token refreshes, subscriptions the server ended,\n * and server errors that answer no request.\n *\n * @param listener - Called with every event from now on.\n * @returns A function that removes the listener.\n */\n on(listener: ClientEventListener): () => void {\n return this.#engine.emitter.on(listener);\n }\n\n /**\n * Removes a listener registered with `on` or `Client.connect`.\n *\n * @param listener - The listener.\n */\n off(listener: ClientEventListener): void {\n this.#engine.emitter.off(listener);\n }\n\n /**\n * Closes the connection and stops the client. Pending requests fail with\n * a `closed` error, every subscription ends, and no timer or socket is\n * left running.\n *\n * @returns A promise that settles once the client has stopped.\n */\n close(): Promise<void> {\n return this.#engine.close();\n }\n\n /**\n * Why the client stopped, if it has.\n *\n * @returns `{ code }` once stopped, where `code` is the close code that\n * stopped it or `null` when the application closed it or it ran out of\n * attempts; `null` while running.\n */\n get stopped(): { code: CloseCode | null } | null {\n return this.#engine.stopped;\n }\n}\n"]}
|