popsub 0.3.0 → 0.4.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/README.md +24 -24
- package/dist/admin.d.ts +30 -0
- package/dist/admin.js +37 -0
- package/dist/admin.js.map +1 -1
- package/dist/config.d.ts +12 -1
- package/dist/config.js +9 -3
- package/dist/config.js.map +1 -1
- package/dist/engine.d.ts +1 -1
- package/dist/engine.js +53 -3
- package/dist/engine.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/protocol.d.ts +22 -1
- package/dist/protocol.js +4 -0
- package/dist/protocol.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -60,20 +60,20 @@ await client.close();
|
|
|
60
60
|
|
|
61
61
|
### `Client`
|
|
62
62
|
|
|
63
|
-
| Member | What it does
|
|
64
|
-
| ------------------------------------------------ |
|
|
65
|
-
| `Client.connect(config, listener?)` | Connects, logs in and authenticates, retrying with the reconnect policy for up to `requestTimeoutMs`. `listener` receives every event, including the first `connected`. Rejects with `invalid_credentials` (and other non-temporary refusals) at once, without retrying.
|
|
66
|
-
| `subscribe(topic, from = "resume")` | Resolves with a `Subscription` once the server confirms it. `topic` is a topic name or a wildcard pattern (below). `from` is `"resume"`, `"new"`, `{ last }`, `{ sinceMs }` or `{ seq }`. Subscribing to a topic or pattern again replaces the earlier subscription.
|
|
67
|
-
| `subscribeShared(topic, group, from = "resume")` | Joins a shared subscription to a topic (below).
|
|
68
|
-
| `unsubscribe(topic)` | Ends the subscription to a topic, or to a pattern and every topic joined through it, and tells the server. While disconnected it is queued and resolves at once.
|
|
69
|
-
| `publish(topic, payload)` | QoS 0. Returns at once. Up to 10,000 publishes (and unsubscribes) are held while disconnected, oldest dropped first. Server refusals arrive as `serverError` events.
|
|
70
|
-
| `publishConfirmed(topic, payload)` | QoS 1. Resolves with `{ seq, messageId }` once stored. Resent after every reconnect until confirmed.
|
|
71
|
-
| `publishBytes(topic, bytes)` | QoS 0 for a `Uint8Array` body that isn't text. Otherwise the same as `publish`. See [Binary payloads](#binary-payloads).
|
|
72
|
-
| `publishBytesConfirmed(topic, bytes)` | QoS 1 for a `Uint8Array` body. Otherwise the same as `publishConfirmed`.
|
|
73
|
-
| `admin()` | An `Admin` with the account calls `createUser`, `getUser`, `listUsers`, `setRole`, `grant`, `revoke`, `setPassword`, `setEnabled` and `deleteUser`, and the topic calls `listTopics`, `getTopic` and `purgeTopic`, which return `TopicInfo` (`name`, `firstSeq`, `lastSeq`, `messages`, `subscribers`). `getTopic` and `purgeTopic` reject with `topic_not_found` for a topic nothing was ever published to. None of these is queued or resent: while disconnected, or when the connection drops before the reply, they reject with `connect`. |
|
|
74
|
-
| `on(listener)` / `off(listener)` | Registers or removes an event listener. `on` returns a function that removes it.
|
|
75
|
-
| `close()` | Stops the client: closes the socket, fails pending requests with `closed`, ends every subscription, clears every timer and listener. Resolves once stopped.
|
|
76
|
-
| `stopped` | `null` while running, then `{ code }` with the close code that stopped it (or `null`).
|
|
63
|
+
| Member | What it does |
|
|
64
|
+
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
65
|
+
| `Client.connect(config, listener?)` | Connects, logs in and authenticates, retrying with the reconnect policy for up to `requestTimeoutMs`. `listener` receives every event, including the first `connected`. Rejects with `invalid_credentials` (and other non-temporary refusals) at once, without retrying. |
|
|
66
|
+
| `subscribe(topic, from = "resume")` | Resolves with a `Subscription` once the server confirms it. `topic` is a topic name or a wildcard pattern (below). `from` is `"resume"`, `"new"`, `{ last }`, `{ sinceMs }` or `{ seq }`. Subscribing to a topic or pattern again replaces the earlier subscription. |
|
|
67
|
+
| `subscribeShared(topic, group, from = "resume")` | Joins a shared subscription to a topic (below). |
|
|
68
|
+
| `unsubscribe(topic)` | Ends the subscription to a topic, or to a pattern and every topic joined through it, and tells the server. While disconnected it is queued and resolves at once. |
|
|
69
|
+
| `publish(topic, payload)` | QoS 0. Returns at once. Up to 10,000 publishes (and unsubscribes) are held while disconnected, oldest dropped first. Server refusals arrive as `serverError` events. |
|
|
70
|
+
| `publishConfirmed(topic, payload)` | QoS 1. Resolves with `{ seq, messageId }` once stored. Resent after every reconnect until confirmed. |
|
|
71
|
+
| `publishBytes(topic, bytes)` | QoS 0 for a `Uint8Array` body that isn't text. Otherwise the same as `publish`. See [Binary payloads](#binary-payloads). |
|
|
72
|
+
| `publishBytesConfirmed(topic, bytes)` | QoS 1 for a `Uint8Array` body. Otherwise the same as `publishConfirmed`. |
|
|
73
|
+
| `admin()` | An `Admin` with the account calls `createUser`, `getUser`, `listUsers`, `setRole`, `grant`, `revoke`, `setPassword`, `setEnabled` and `deleteUser`, and the topic calls `listTopics`, `getTopic` and `purgeTopic`, which return `TopicInfo` (`name`, `firstSeq`, `lastSeq`, `messages`, `subscribers`). `getTopic` and `purgeTopic` reject with `topic_not_found` for a topic nothing was ever published to. None of these is queued or resent: while disconnected, or when the connection drops before the reply, they reject with `connect`. `backup(name?)` asks the server to back itself up and returns `BackupInfo` (`name`, `path`, `topics`, `records`, `bytes`, `users`) when the copy is done, which can take longer than the default `requestTimeoutMs`. |
|
|
74
|
+
| `on(listener)` / `off(listener)` | Registers or removes an event listener. `on` returns a function that removes it. |
|
|
75
|
+
| `close()` | Stops the client: closes the socket, fails pending requests with `closed`, ends every subscription, clears every timer and listener. Resolves once stopped. |
|
|
76
|
+
| `stopped` | `null` while running, then `{ code }` with the close code that stopped it (or `null`). |
|
|
77
77
|
|
|
78
78
|
### Wildcard subscriptions
|
|
79
79
|
|
|
@@ -151,16 +151,16 @@ Every failure is a `PopSubError` with `kind` (`server`, `closed`, `timeout`, `co
|
|
|
151
151
|
|
|
152
152
|
### Configuration
|
|
153
153
|
|
|
154
|
-
| Field | Default | Meaning
|
|
155
|
-
| -------------------- | ----------------------------------------------------- |
|
|
156
|
-
| `url` | required | `ws://` or `wss://`
|
|
157
|
-
| `credentials` | required | `{ username, password }`,
|
|
158
|
-
| `sessionId` | `null` | A durable session, 1 to 128 characters
|
|
159
|
-
| `cleanStart` | `false` | Discard the session's stored subscriptions, on the first connection only
|
|
160
|
-
| `ackMode` | `"auto"` | `"auto"` or `"manual"`
|
|
161
|
-
| `reconnect` | `{ initialMs: 250, maxMs: 30000, maxAttempts: null }` | Each wait is random between zero and a ceiling that doubles from `initialMs` up to `maxMs`
|
|
162
|
-
| `requestTimeoutMs` | `30000` | Limit for connect, subscribe, unsubscribe, confirmed publishes and admin calls
|
|
163
|
-
| `subscriptionBuffer` | `1024` | Messages buffered per subscription before the client holds back (below)
|
|
154
|
+
| Field | Default | Meaning |
|
|
155
|
+
| -------------------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
156
|
+
| `url` | required | `ws://` or `wss://` |
|
|
157
|
+
| `credentials` | required | `{ username, password }`, `{ token }` (a token can't be refreshed; the client stops when it expires), or `{ tokenProvider }`, an async function returning a fresh token, called on every connection and when the server warns the token is about to expire |
|
|
158
|
+
| `sessionId` | `null` | A durable session, 1 to 128 characters |
|
|
159
|
+
| `cleanStart` | `false` | Discard the session's stored subscriptions, on the first connection only |
|
|
160
|
+
| `ackMode` | `"auto"` | `"auto"` or `"manual"` |
|
|
161
|
+
| `reconnect` | `{ initialMs: 250, maxMs: 30000, maxAttempts: null }` | Each wait is random between zero and a ceiling that doubles from `initialMs` up to `maxMs` |
|
|
162
|
+
| `requestTimeoutMs` | `30000` | Limit for connect, subscribe, unsubscribe, confirmed publishes and admin calls |
|
|
163
|
+
| `subscriptionBuffer` | `1024` | Messages buffered per subscription before the client holds back (below) |
|
|
164
164
|
|
|
165
165
|
## How it differs from the Rust client
|
|
166
166
|
|
package/dist/admin.d.ts
CHANGED
|
@@ -35,6 +35,21 @@ export interface TopicInfo {
|
|
|
35
35
|
/** How many live subscriptions it has. */
|
|
36
36
|
subscribers: number;
|
|
37
37
|
}
|
|
38
|
+
/** A backup the server wrote of itself. */
|
|
39
|
+
export interface BackupInfo {
|
|
40
|
+
/** The backup's directory name. */
|
|
41
|
+
name: string;
|
|
42
|
+
/** Where the backup is on the server's file system. */
|
|
43
|
+
path: string;
|
|
44
|
+
/** How many topics it holds. */
|
|
45
|
+
topics: number;
|
|
46
|
+
/** How many records it holds across every topic. */
|
|
47
|
+
records: number;
|
|
48
|
+
/** How many bytes were written. */
|
|
49
|
+
bytes: number;
|
|
50
|
+
/** Whether accounts were included; false when the server doesn't keep them in `users.json`. */
|
|
51
|
+
users: boolean;
|
|
52
|
+
}
|
|
38
53
|
/** Sends one admin request and returns its reply. */
|
|
39
54
|
export type AdminTransport = (request: AdminRequest) => Promise<ServerMessage>;
|
|
40
55
|
/**
|
|
@@ -172,4 +187,19 @@ export declare class Admin {
|
|
|
172
187
|
* published to it.
|
|
173
188
|
*/
|
|
174
189
|
purgeTopic(topic: string): Promise<TopicInfo>;
|
|
190
|
+
/**
|
|
191
|
+
* Asks the server to back itself up while it keeps running: its topic
|
|
192
|
+
* logs, sessions and accounts, into a new directory under its
|
|
193
|
+
* `storage.backup_path`. The reply comes when the copy is finished, which
|
|
194
|
+
* for a large store can take longer than the default `requestTimeoutMs`;
|
|
195
|
+
* use a client with a longer one for backups.
|
|
196
|
+
*
|
|
197
|
+
* @param name - The backup's directory name. Defaults to the time in UTC,
|
|
198
|
+
* such as `20261127T101500Z`.
|
|
199
|
+
* @returns The backup's name, where it is on the server, and what it holds.
|
|
200
|
+
* @throws PopSubError with code `backup_exists`, `backup_unsupported` for
|
|
201
|
+
* the memory backend, `bad_request` for an invalid name, or
|
|
202
|
+
* `storage_unavailable` when another backup is running.
|
|
203
|
+
*/
|
|
204
|
+
backup(name?: string): Promise<BackupInfo>;
|
|
175
205
|
}
|
package/dist/admin.js
CHANGED
|
@@ -11,6 +11,22 @@
|
|
|
11
11
|
* @module
|
|
12
12
|
*/
|
|
13
13
|
import { PopSubError } from "./errors.js";
|
|
14
|
+
/**
|
|
15
|
+
* Converts a backup from its wire form.
|
|
16
|
+
*
|
|
17
|
+
* @param backup - The backup as the server sent it.
|
|
18
|
+
* @returns The backup.
|
|
19
|
+
*/
|
|
20
|
+
function backupFromWire(backup) {
|
|
21
|
+
return {
|
|
22
|
+
name: backup.name,
|
|
23
|
+
path: backup.path,
|
|
24
|
+
topics: backup.topics,
|
|
25
|
+
records: backup.records,
|
|
26
|
+
bytes: backup.bytes,
|
|
27
|
+
users: backup.users,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
14
30
|
/**
|
|
15
31
|
* Converts a topic from its wire form.
|
|
16
32
|
*
|
|
@@ -223,6 +239,27 @@ export class Admin {
|
|
|
223
239
|
purgeTopic(topic) {
|
|
224
240
|
return this.#topic({ type: "purge_topic", topic });
|
|
225
241
|
}
|
|
242
|
+
/**
|
|
243
|
+
* Asks the server to back itself up while it keeps running: its topic
|
|
244
|
+
* logs, sessions and accounts, into a new directory under its
|
|
245
|
+
* `storage.backup_path`. The reply comes when the copy is finished, which
|
|
246
|
+
* for a large store can take longer than the default `requestTimeoutMs`;
|
|
247
|
+
* use a client with a longer one for backups.
|
|
248
|
+
*
|
|
249
|
+
* @param name - The backup's directory name. Defaults to the time in UTC,
|
|
250
|
+
* such as `20261127T101500Z`.
|
|
251
|
+
* @returns The backup's name, where it is on the server, and what it holds.
|
|
252
|
+
* @throws PopSubError with code `backup_exists`, `backup_unsupported` for
|
|
253
|
+
* the memory backend, `bad_request` for an invalid name, or
|
|
254
|
+
* `storage_unavailable` when another backup is running.
|
|
255
|
+
*/
|
|
256
|
+
async backup(name) {
|
|
257
|
+
const reply = await this.#send(name === undefined ? { type: "backup" } : { type: "backup", name });
|
|
258
|
+
if (reply.type !== "backup_created") {
|
|
259
|
+
throw unexpected(reply, "backup_created");
|
|
260
|
+
}
|
|
261
|
+
return backupFromWire(reply.backup);
|
|
262
|
+
}
|
|
226
263
|
/**
|
|
227
264
|
* Sends a request answered by a `topic_info` frame.
|
|
228
265
|
*
|
package/dist/admin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AA6B1C;;;;;GAKG;AACH,SAAS,aAAa,CAAC,KAAoB;IACzC,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,QAAQ,EAAE,KAAK,CAAC,SAAS;QACzB,OAAO,EAAE,KAAK,CAAC,QAAQ;QACvB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC;AACJ,CAAC;AAKD;;;;;GAKG;AACH,SAAS,QAAQ,CAAC,IAAc;IAC9B,OAAO;QACL,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,WAAW,EAAE,IAAI,CAAC,aAAa;KAChC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,UAAU,CAAC,KAAoB,EAAE,QAAgB;IACxD,OAAO,IAAI,WAAW,CAAC,UAAU,EAAE,cAAc,QAAQ,eAAe,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;AACxF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,KAAK;IAChB,0BAA0B;IACjB,KAAK,CAAiB;IAE/B;;;;OAIG;IACH,YAAY,IAAoB;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IACpB,CAAC;IAED;;;;;;;;;OASG;IACH,UAAU,CAAC,QAAgB,EAAE,QAAgB,EAAE,IAAc;QAC3D,OAAO,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,aAAa,E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C,OAAO,CAAC,CAAC;QACxC,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YAChC,MAAM,UAAU,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;QACxC,CAAC;QACD,OAAO,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,KAAK,CAAC,OAAqB;QAC/B,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACxC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAC1B,MAAM,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/**\n * `Admin`, the account management requests, for clients logged in as an\n * admin.\n *\n * Each call is one request and its reply. None is queued while the client\n * is disconnected or resent after a reconnect, because repeating a change\n * such as `createUser` isn't safe: a call made while disconnected fails\n * with a `connect` error, and so does one whose connection drops before the\n * reply, whether or not the server carried it out.\n *\n * @module\n */\n\nimport { PopSubError } from \"./errors.js\";\nimport type { Access, AdminRequest, RoleSpec, ServerMessage, WireTopicInfo, WireUser } from \"./protocol.js\";\n\n/** An account, as admins see it. Never includes the password. */\nexport interface User {\n /** The username. */\n username: string;\n /** What it may do. */\n role: RoleSpec;\n /** Whether it may log in and use topics. */\n enabled: boolean;\n /** When it was created, in milliseconds since the Unix epoch. */\n createdAtMs: number;\n}\n\n/** A topic, as admins see it. */\nexport interface TopicInfo {\n /** The topic's name. */\n name: string;\n /** The oldest `seq` still kept, or `lastSeq + 1` when nothing is kept. */\n firstSeq: number;\n /** The newest `seq` ever published. */\n lastSeq: number;\n /** How many records are kept now. */\n messages: number;\n /** How many live subscriptions it has. */\n subscribers: number;\n}\n\n/**\n * Converts a topic from its wire form.\n *\n * @param topic - The topic as the server sent it.\n * @returns The topic.\n */\nfunction topicFromWire(topic: WireTopicInfo): TopicInfo {\n return {\n name: topic.name,\n firstSeq: topic.first_seq,\n lastSeq: topic.last_seq,\n messages: topic.messages,\n subscribers: topic.subscribers,\n };\n}\n\n/** Sends one admin request and returns its reply. */\nexport type AdminTransport = (request: AdminRequest) => Promise<ServerMessage>;\n\n/**\n * Converts an account from its wire form.\n *\n * @param user - The account as the server sent it.\n * @returns The account.\n */\nfunction fromWire(user: WireUser): User {\n return {\n username: user.username,\n role: user.role,\n enabled: user.enabled,\n createdAtMs: user.created_at_ms,\n };\n}\n\n/**\n * Builds the error for a reply of the wrong type.\n *\n * @param reply - What the server sent.\n * @param expected - The type that was expected.\n * @returns The `protocol` error.\n */\nfunction unexpected(reply: ServerMessage, expected: string): PopSubError {\n return new PopSubError(\"protocol\", `expected a ${expected} reply, got ${reply.type}`);\n}\n\n/**\n * The admin requests, from `Client.admin`. Every call rejects with a\n * `server` error with code `forbidden` unless the client is logged in as\n * an enabled admin, `connect` when disconnected or when the connection\n * drops before the reply, `timeout` when no reply arrives in time, and\n * `closed` when the client has stopped.\n */\nexport class Admin {\n /** Sends the requests. */\n readonly #send: AdminTransport;\n\n /**\n * Wraps a transport. Applications get an `Admin` from `Client.admin`.\n *\n * @param send - Sends one request and returns its reply.\n */\n constructor(send: AdminTransport) {\n this.#send = send;\n }\n\n /**\n * Creates an account.\n *\n * @param username - Its name: 3 to 32 letters, digits, `_`, `.` or `-`.\n * @param password - Its password, at least 8 characters.\n * @param role - What it may do.\n * @returns The new account.\n * @throws PopSubError with code `user_exists`, or `bad_request` for an\n * invalid name, password or pattern.\n */\n createUser(username: string, password: string, role: RoleSpec): Promise<User> {\n return this.#user({ type: \"create_user\", username, password, role });\n }\n\n /**\n * Reads an account.\n *\n * @param username - The account.\n * @returns The account.\n * @throws PopSubError with code `user_not_found`.\n */\n getUser(username: string): Promise<User> {\n return this.#user({ type: \"get_user\", username });\n }\n\n /**\n * Lists every account, sorted by name.\n *\n * @returns The accounts.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `users`.\n */\n async listUsers(): Promise<User[]> {\n const reply = await this.#send({ type: \"list_users\" });\n if (reply.type !== \"users\") {\n throw unexpected(reply, \"users\");\n }\n return reply.users.map(fromWire);\n }\n\n /**\n * Replaces an account's role. Live subscriptions the new role doesn't\n * allow are ended.\n *\n * @param username - The account.\n * @param role - Its new role.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for an\n * invalid pattern or for demoting the last enabled admin.\n */\n setRole(username: string, role: RoleSpec): Promise<User> {\n return this.#user({ type: \"set_role\", username, role });\n }\n\n /**\n * Grants an account a topic pattern, replacing any grant it already has\n * for exactly that pattern.\n *\n * @param username - The account.\n * @param pattern - The topic pattern.\n * @param access - What it allows.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for an\n * invalid pattern, an admin account, or publishing for a readonly one.\n */\n grant(username: string, pattern: string, access: Access): Promise<User> {\n return this.#user({ type: \"grant\", username, pattern, access });\n }\n\n /**\n * Removes one of an account's grants. Live subscriptions no longer\n * allowed are ended.\n *\n * @param username - The account.\n * @param pattern - The pattern, exactly as granted.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` when\n * the account has no such grant.\n */\n revoke(username: string, pattern: string): Promise<User> {\n return this.#user({ type: \"revoke\", username, pattern });\n }\n\n /**\n * Sets an account's password. Tokens issued before it are cancelled, and\n * the account's connections are closed so they log in again.\n *\n * @param username - The account.\n * @param password - The new password.\n * @returns The account.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for a\n * password that is too short or too long.\n */\n setPassword(username: string, password: string): Promise<User> {\n return this.#user({ type: \"set_password\", username, password });\n }\n\n /**\n * Enables or disables an account. Disabling closes its connections with\n * `account_disabled` (4009) and refuses its logins and tokens.\n *\n * @param username - The account.\n * @param enabled - Whether it may log in.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for\n * disabling the last enabled admin.\n */\n setEnabled(username: string, enabled: boolean): Promise<User> {\n return this.#user({ type: \"set_enabled\", username, enabled });\n }\n\n /**\n * Deletes an account and closes its connections with `account_disabled` (4009).\n *\n * @param username - The account.\n * @throws PopSubError with code `user_not_found`, `bad_request` for the\n * last enabled admin, or of kind `protocol` when the server answers\n * with something other than `user_deleted`.\n */\n async deleteUser(username: string): Promise<void> {\n const reply = await this.#send({ type: \"delete_user\", username });\n if (reply.type !== \"user_deleted\") {\n throw unexpected(reply, \"user_deleted\");\n }\n }\n\n /**\n * Lists every topic that has a log, sorted by name.\n *\n * @returns The topics.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `topics`.\n */\n async listTopics(): Promise<TopicInfo[]> {\n const reply = await this.#send({ type: \"list_topics\" });\n if (reply.type !== \"topics\") {\n throw unexpected(reply, \"topics\");\n }\n return reply.topics.map(topicFromWire);\n }\n\n /**\n * Reads a topic's bounds, record count and live subscriptions.\n *\n * @param topic - The topic.\n * @returns The topic.\n * @throws PopSubError with code `topic_not_found` when nothing was ever\n * published to it.\n */\n getTopic(topic: string): Promise<TopicInfo> {\n return this.#topic({ type: \"get_topic\", topic });\n }\n\n /**\n * Removes every record a topic holds. Its numbering carries on (the next\n * publish gets `lastSeq + 1`), live subscriptions stay, and a subscriber\n * that hadn't caught up gets `truncated`.\n *\n * @param topic - The topic.\n * @returns The topic after the purge.\n * @throws PopSubError with code `topic_not_found` when nothing was ever\n * published to it.\n */\n purgeTopic(topic: string): Promise<TopicInfo> {\n return this.#topic({ type: \"purge_topic\", topic });\n }\n\n /**\n * Sends a request answered by a `topic_info` frame.\n *\n * @param request - The request.\n * @returns The topic in the reply.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `topic_info`.\n */\n async #topic(request: AdminRequest): Promise<TopicInfo> {\n const reply = await this.#send(request);\n if (reply.type !== \"topic_info\") {\n throw unexpected(reply, \"topic_info\");\n }\n return topicFromWire(reply.topic);\n }\n\n /**\n * Sends a request answered by a `user` frame.\n *\n * @param request - The request.\n * @returns The account in the reply.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `user`.\n */\n async #user(request: AdminRequest): Promise<User> {\n const reply = await this.#send(request);\n if (reply.type !== \"user\") {\n throw unexpected(reply, \"user\");\n }\n return fromWire(reply.user);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAqD1C;;;;;GAKG;AACH,SAAS,cAAc,CAAC,MAAsB;IAC5C,OAAO;QACL,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAC,KAAoB;IACzC,OAAO;QACL,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,QAAQ,EAAE,KAAK,CAAC,SAAS;QACzB,OAAO,EAAE,KAAK,CAAC,QAAQ;QACvB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,WAAW,EAAE,KAAK,CAAC,WAAW;KAC/B,CAAC;AACJ,CAAC;AAKD;;;;;GAKG;AACH,SAAS,QAAQ,CAAC,IAAc;IAC9B,OAAO;QACL,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,WAAW,EAAE,IAAI,CAAC,aAAa;KAChC,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,UAAU,CAAC,KAAoB,EAAE,QAAgB;IACxD,OAAO,IAAI,WAAW,CAAC,UA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AAK,EAAE,MAAM,CAAC,CAAC;QAClC,CAAC;QACD,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;CACF","sourcesContent":["/**\n * `Admin`, the account management requests, for clients logged in as an\n * admin.\n *\n * Each call is one request and its reply. None is queued while the client\n * is disconnected or resent after a reconnect, because repeating a change\n * such as `createUser` isn't safe: a call made while disconnected fails\n * with a `connect` error, and so does one whose connection drops before the\n * reply, whether or not the server carried it out.\n *\n * @module\n */\n\nimport { PopSubError } from \"./errors.js\";\nimport type {\n Access,\n AdminRequest,\n RoleSpec,\n ServerMessage,\n WireBackupInfo,\n WireTopicInfo,\n WireUser,\n} from \"./protocol.js\";\n\n/** An account, as admins see it. Never includes the password. */\nexport interface User {\n /** The username. */\n username: string;\n /** What it may do. */\n role: RoleSpec;\n /** Whether it may log in and use topics. */\n enabled: boolean;\n /** When it was created, in milliseconds since the Unix epoch. */\n createdAtMs: number;\n}\n\n/** A topic, as admins see it. */\nexport interface TopicInfo {\n /** The topic's name. */\n name: string;\n /** The oldest `seq` still kept, or `lastSeq + 1` when nothing is kept. */\n firstSeq: number;\n /** The newest `seq` ever published. */\n lastSeq: number;\n /** How many records are kept now. */\n messages: number;\n /** How many live subscriptions it has. */\n subscribers: number;\n}\n\n/** A backup the server wrote of itself. */\nexport interface BackupInfo {\n /** The backup's directory name. */\n name: string;\n /** Where the backup is on the server's file system. */\n path: string;\n /** How many topics it holds. */\n topics: number;\n /** How many records it holds across every topic. */\n records: number;\n /** How many bytes were written. */\n bytes: number;\n /** Whether accounts were included; false when the server doesn't keep them in `users.json`. */\n users: boolean;\n}\n\n/**\n * Converts a backup from its wire form.\n *\n * @param backup - The backup as the server sent it.\n * @returns The backup.\n */\nfunction backupFromWire(backup: WireBackupInfo): BackupInfo {\n return {\n name: backup.name,\n path: backup.path,\n topics: backup.topics,\n records: backup.records,\n bytes: backup.bytes,\n users: backup.users,\n };\n}\n\n/**\n * Converts a topic from its wire form.\n *\n * @param topic - The topic as the server sent it.\n * @returns The topic.\n */\nfunction topicFromWire(topic: WireTopicInfo): TopicInfo {\n return {\n name: topic.name,\n firstSeq: topic.first_seq,\n lastSeq: topic.last_seq,\n messages: topic.messages,\n subscribers: topic.subscribers,\n };\n}\n\n/** Sends one admin request and returns its reply. */\nexport type AdminTransport = (request: AdminRequest) => Promise<ServerMessage>;\n\n/**\n * Converts an account from its wire form.\n *\n * @param user - The account as the server sent it.\n * @returns The account.\n */\nfunction fromWire(user: WireUser): User {\n return {\n username: user.username,\n role: user.role,\n enabled: user.enabled,\n createdAtMs: user.created_at_ms,\n };\n}\n\n/**\n * Builds the error for a reply of the wrong type.\n *\n * @param reply - What the server sent.\n * @param expected - The type that was expected.\n * @returns The `protocol` error.\n */\nfunction unexpected(reply: ServerMessage, expected: string): PopSubError {\n return new PopSubError(\"protocol\", `expected a ${expected} reply, got ${reply.type}`);\n}\n\n/**\n * The admin requests, from `Client.admin`. Every call rejects with a\n * `server` error with code `forbidden` unless the client is logged in as\n * an enabled admin, `connect` when disconnected or when the connection\n * drops before the reply, `timeout` when no reply arrives in time, and\n * `closed` when the client has stopped.\n */\nexport class Admin {\n /** Sends the requests. */\n readonly #send: AdminTransport;\n\n /**\n * Wraps a transport. Applications get an `Admin` from `Client.admin`.\n *\n * @param send - Sends one request and returns its reply.\n */\n constructor(send: AdminTransport) {\n this.#send = send;\n }\n\n /**\n * Creates an account.\n *\n * @param username - Its name: 3 to 32 letters, digits, `_`, `.` or `-`.\n * @param password - Its password, at least 8 characters.\n * @param role - What it may do.\n * @returns The new account.\n * @throws PopSubError with code `user_exists`, or `bad_request` for an\n * invalid name, password or pattern.\n */\n createUser(username: string, password: string, role: RoleSpec): Promise<User> {\n return this.#user({ type: \"create_user\", username, password, role });\n }\n\n /**\n * Reads an account.\n *\n * @param username - The account.\n * @returns The account.\n * @throws PopSubError with code `user_not_found`.\n */\n getUser(username: string): Promise<User> {\n return this.#user({ type: \"get_user\", username });\n }\n\n /**\n * Lists every account, sorted by name.\n *\n * @returns The accounts.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `users`.\n */\n async listUsers(): Promise<User[]> {\n const reply = await this.#send({ type: \"list_users\" });\n if (reply.type !== \"users\") {\n throw unexpected(reply, \"users\");\n }\n return reply.users.map(fromWire);\n }\n\n /**\n * Replaces an account's role. Live subscriptions the new role doesn't\n * allow are ended.\n *\n * @param username - The account.\n * @param role - Its new role.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for an\n * invalid pattern or for demoting the last enabled admin.\n */\n setRole(username: string, role: RoleSpec): Promise<User> {\n return this.#user({ type: \"set_role\", username, role });\n }\n\n /**\n * Grants an account a topic pattern, replacing any grant it already has\n * for exactly that pattern.\n *\n * @param username - The account.\n * @param pattern - The topic pattern.\n * @param access - What it allows.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for an\n * invalid pattern, an admin account, or publishing for a readonly one.\n */\n grant(username: string, pattern: string, access: Access): Promise<User> {\n return this.#user({ type: \"grant\", username, pattern, access });\n }\n\n /**\n * Removes one of an account's grants. Live subscriptions no longer\n * allowed are ended.\n *\n * @param username - The account.\n * @param pattern - The pattern, exactly as granted.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` when\n * the account has no such grant.\n */\n revoke(username: string, pattern: string): Promise<User> {\n return this.#user({ type: \"revoke\", username, pattern });\n }\n\n /**\n * Sets an account's password. Tokens issued before it are cancelled, and\n * the account's connections are closed so they log in again.\n *\n * @param username - The account.\n * @param password - The new password.\n * @returns The account.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for a\n * password that is too short or too long.\n */\n setPassword(username: string, password: string): Promise<User> {\n return this.#user({ type: \"set_password\", username, password });\n }\n\n /**\n * Enables or disables an account. Disabling closes its connections with\n * `account_disabled` (4009) and refuses its logins and tokens.\n *\n * @param username - The account.\n * @param enabled - Whether it may log in.\n * @returns The account as it now stands.\n * @throws PopSubError with code `user_not_found`, or `bad_request` for\n * disabling the last enabled admin.\n */\n setEnabled(username: string, enabled: boolean): Promise<User> {\n return this.#user({ type: \"set_enabled\", username, enabled });\n }\n\n /**\n * Deletes an account and closes its connections with `account_disabled` (4009).\n *\n * @param username - The account.\n * @throws PopSubError with code `user_not_found`, `bad_request` for the\n * last enabled admin, or of kind `protocol` when the server answers\n * with something other than `user_deleted`.\n */\n async deleteUser(username: string): Promise<void> {\n const reply = await this.#send({ type: \"delete_user\", username });\n if (reply.type !== \"user_deleted\") {\n throw unexpected(reply, \"user_deleted\");\n }\n }\n\n /**\n * Lists every topic that has a log, sorted by name.\n *\n * @returns The topics.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `topics`.\n */\n async listTopics(): Promise<TopicInfo[]> {\n const reply = await this.#send({ type: \"list_topics\" });\n if (reply.type !== \"topics\") {\n throw unexpected(reply, \"topics\");\n }\n return reply.topics.map(topicFromWire);\n }\n\n /**\n * Reads a topic's bounds, record count and live subscriptions.\n *\n * @param topic - The topic.\n * @returns The topic.\n * @throws PopSubError with code `topic_not_found` when nothing was ever\n * published to it.\n */\n getTopic(topic: string): Promise<TopicInfo> {\n return this.#topic({ type: \"get_topic\", topic });\n }\n\n /**\n * Removes every record a topic holds. Its numbering carries on (the next\n * publish gets `lastSeq + 1`), live subscriptions stay, and a subscriber\n * that hadn't caught up gets `truncated`.\n *\n * @param topic - The topic.\n * @returns The topic after the purge.\n * @throws PopSubError with code `topic_not_found` when nothing was ever\n * published to it.\n */\n purgeTopic(topic: string): Promise<TopicInfo> {\n return this.#topic({ type: \"purge_topic\", topic });\n }\n\n /**\n * Asks the server to back itself up while it keeps running: its topic\n * logs, sessions and accounts, into a new directory under its\n * `storage.backup_path`. The reply comes when the copy is finished, which\n * for a large store can take longer than the default `requestTimeoutMs`;\n * use a client with a longer one for backups.\n *\n * @param name - The backup's directory name. Defaults to the time in UTC,\n * such as `20261127T101500Z`.\n * @returns The backup's name, where it is on the server, and what it holds.\n * @throws PopSubError with code `backup_exists`, `backup_unsupported` for\n * the memory backend, `bad_request` for an invalid name, or\n * `storage_unavailable` when another backup is running.\n */\n async backup(name?: string): Promise<BackupInfo> {\n const reply = await this.#send(name === undefined ? { type: \"backup\" } : { type: \"backup\", name });\n if (reply.type !== \"backup_created\") {\n throw unexpected(reply, \"backup_created\");\n }\n return backupFromWire(reply.backup);\n }\n\n /**\n * Sends a request answered by a `topic_info` frame.\n *\n * @param request - The request.\n * @returns The topic in the reply.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `topic_info`.\n */\n async #topic(request: AdminRequest): Promise<TopicInfo> {\n const reply = await this.#send(request);\n if (reply.type !== \"topic_info\") {\n throw unexpected(reply, \"topic_info\");\n }\n return topicFromWire(reply.topic);\n }\n\n /**\n * Sends a request answered by a `user` frame.\n *\n * @param request - The request.\n * @returns The account in the reply.\n * @throws PopSubError of kind `protocol` when the server answers with\n * something other than `user`.\n */\n async #user(request: AdminRequest): Promise<User> {\n const reply = await this.#send(request);\n if (reply.type !== \"user\") {\n throw unexpected(reply, \"user\");\n }\n return fromWire(reply.user);\n }\n}\n"]}
|
package/dist/config.d.ts
CHANGED
|
@@ -23,8 +23,19 @@ export interface TokenCredentials {
|
|
|
23
23
|
/** The token. */
|
|
24
24
|
token: string;
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* A function that fetches a fresh token, such as from your backend, which
|
|
28
|
+
* signs short-lived tokens for its signed-in users. The client calls it on
|
|
29
|
+
* every connection, when the server warns the token is about to expire, and
|
|
30
|
+
* to reconnect after it did expire. A rejection is retried like a failed
|
|
31
|
+
* connection.
|
|
32
|
+
*/
|
|
33
|
+
export interface ProviderCredentials {
|
|
34
|
+
/** Returns a fresh token. */
|
|
35
|
+
tokenProvider: () => Promise<string>;
|
|
36
|
+
}
|
|
26
37
|
/** How the client proves who it is. */
|
|
27
|
-
export type Credentials = PasswordCredentials | TokenCredentials;
|
|
38
|
+
export type Credentials = PasswordCredentials | TokenCredentials | ProviderCredentials;
|
|
28
39
|
/**
|
|
29
40
|
* When QoS 1 messages are acknowledged.
|
|
30
41
|
*
|
package/dist/config.js
CHANGED
|
@@ -45,14 +45,20 @@ function positive(name, value) {
|
|
|
45
45
|
* @param credentials - The credentials.
|
|
46
46
|
* @returns The copy.
|
|
47
47
|
* @throws PopSubError of kind `config` when they are neither a username and
|
|
48
|
-
* password nor a token.
|
|
48
|
+
* password, a token, nor a token provider.
|
|
49
49
|
*/
|
|
50
50
|
function checkCredentials(credentials) {
|
|
51
51
|
if (typeof credentials !== "object" || credentials === null) {
|
|
52
52
|
throw invalid("credentials are required");
|
|
53
53
|
}
|
|
54
54
|
const fields = credentials;
|
|
55
|
-
const { token, username, password } = fields;
|
|
55
|
+
const { token, username, password, tokenProvider } = fields;
|
|
56
|
+
if ("tokenProvider" in fields) {
|
|
57
|
+
if (typeof tokenProvider !== "function") {
|
|
58
|
+
throw invalid("the token provider must be a function");
|
|
59
|
+
}
|
|
60
|
+
return { tokenProvider: tokenProvider };
|
|
61
|
+
}
|
|
56
62
|
if ("token" in fields) {
|
|
57
63
|
if (typeof token !== "string" || token === "") {
|
|
58
64
|
throw invalid("the token must be a non-empty string");
|
|
@@ -60,7 +66,7 @@ function checkCredentials(credentials) {
|
|
|
60
66
|
return { token };
|
|
61
67
|
}
|
|
62
68
|
if (typeof username !== "string" || typeof password !== "string") {
|
|
63
|
-
throw invalid("credentials need a username and password, or a token");
|
|
69
|
+
throw invalid("credentials need a username and password, a token, or a token provider");
|
|
64
70
|
}
|
|
65
71
|
return { username, password };
|
|
66
72
|
}
|
package/dist/config.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAuG1C,yEAAyE;AACzE,MAAM,CAAC,MAAM,iBAAiB,GAA8B,MAAM,CAAC,MAAM,CAAC;IAC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AAI;QAC9B,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI,SAAS,CAAC,WAAW,GAAG,CAAC,CAAC,EACvE,CAAC;QACD,MAAM,OAAO,CAAC,qEAAqE,CAAC,CAAC;IACvF,CAAC;IACD,MAAM,kBAAkB,GAAG,MAAM,CAAC,kBAAkB,IAAI,2BAA2B,CAAC;IACpF,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,kBAAkB,CAAC,IAAI,kBAAkB,GAAG,CAAC,EAAE,CAAC;QACpE,MAAM,OAAO,CAAC,yDAAyD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO;QACL,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,WAAW,EAAE,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC;QACjD,SAAS;QACT,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,KAAK;QACtC,OAAO;QACP,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC,gBAAgB,IAAI,0BAA0B,CAAC;QACrG,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * How a `Client` connects: where, as whom, and how it behaves when things\n * go wrong. `resolveConfig` fills in defaults and rejects invalid values.\n *\n * @module\n */\n\nimport { PopSubError } from \"./errors.js\";\n\n/**\n * A username and password. The client logs in on every connection and\n * refreshes its token on its own before it expires.\n */\nexport interface PasswordCredentials {\n /** The username. */\n username: string;\n /** The password. */\n password: string;\n}\n\n/**\n * A JWT obtained elsewhere. The client can't refresh it: when it expires\n * the server closes the connection with `token_expired` and the client\n * stops, after an `authExpiring` event.\n */\nexport interface TokenCredentials {\n /** The token. */\n token: string;\n}\n\n/** How the client proves who it is. */\nexport type Credentials = PasswordCredentials | TokenCredentials;\n\n/**\n * When QoS 1 messages are acknowledged.\n *\n * - `auto`: as the client hands them to the subscription's buffer (or, when\n * the buffer is full, as the application takes them). A message the\n * application was processing when it crashed isn't redelivered.\n * - `manual`: when the application calls `Message.ack`. A message never\n * acknowledged is redelivered after a reconnect (to a durable session),\n * and stalls its subscription once the server runs out of retries.\n */\nexport type AckMode = \"auto\" | \"manual\";\n\n/**\n * How the client waits between reconnection attempts: a random wait\n * between zero and a ceiling that doubles from `initialMs` up to `maxMs`.\n */\nexport interface ReconnectPolicy {\n /** The starting ceiling, in milliseconds. */\n initialMs: number;\n /** The highest ceiling, in milliseconds. */\n maxMs: number;\n /** Give up after this many failed attempts in a row; `null` keeps trying. */\n maxAttempts: number | null;\n}\n\n/** Everything a `Client` needs to connect. Only `url` and `credentials` are required. */\nexport interface ClientConfig {\n /** The server's WebSocket URL, such as `ws://127.0.0.1:8080`, or `wss://` for TLS. */\n url: string;\n /** Who to connect as. */\n credentials: Credentials;\n /**\n * A durable session to hold, 1 to 128 characters, so subscriptions and\n * unacknowledged messages survive disconnects. Absent or `null` is an\n * ephemeral connection.\n */\n sessionId?: string | null;\n /** Discard the session's stored subscriptions on the first connection. Never sent on reconnects. */\n cleanStart?: boolean;\n /** When QoS 1 messages are acknowledged; `auto` by default. */\n ackMode?: AckMode;\n /** How to reconnect; 250 ms doubling up to 30 seconds, forever, by default. */\n reconnect?: Partial<ReconnectPolicy>;\n /**\n * How long a request (connect, subscribe, unsubscribe, confirmed publish,\n * admin call) may take, reconnects included, in milliseconds; 30 seconds\n * by default.\n */\n requestTimeoutMs?: number;\n /**\n * How many messages each subscription buffers for the application before\n * the client starts holding back; 1024 by default. See the README's\n * section on backpressure for what happens beyond it.\n */\n subscriptionBuffer?: number;\n}\n\n/** A `ClientConfig` with every default filled in. */\nexport interface ResolvedConfig {\n /** The server's WebSocket URL. */\n url: string;\n /** Who to connect as. */\n credentials: Credentials;\n /** The durable session, or `null` for an ephemeral connection. */\n sessionId: string | null;\n /** Whether the first connection discards the session's stored subscriptions. */\n cleanStart: boolean;\n /** When QoS 1 messages are acknowledged. */\n ackMode: AckMode;\n /** How to reconnect. */\n reconnect: ReconnectPolicy;\n /** How long a request may take, in milliseconds. */\n requestTimeoutMs: number;\n /** How many messages each subscription buffers before holding back. */\n subscriptionBuffer: number;\n}\n\n/** The reconnect policy used for fields the configuration leaves out. */\nexport const DEFAULT_RECONNECT: Readonly<ReconnectPolicy> = Object.freeze({\n initialMs: 250,\n maxMs: 30_000,\n maxAttempts: null,\n});\n\n/** The request timeout used when the configuration leaves it out. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** The subscription buffer size used when the configuration leaves it out. */\nexport const DEFAULT_SUBSCRIPTION_BUFFER = 1024;\n\n/**\n * Builds the error for an invalid setting.\n *\n * @param message - What is wrong.\n * @returns The `config` error.\n */\nfunction invalid(message: string): PopSubError {\n return new PopSubError(\"config\", `invalid configuration: ${message}`);\n}\n\n/**\n * Checks that a setting is a positive, finite number.\n *\n * @param name - The setting's name, for the error.\n * @param value - Its value.\n * @returns The value.\n * @throws PopSubError of kind `config` when it isn't.\n */\nfunction positive(name: string, value: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw invalid(`${name} must be a positive number`);\n }\n return value;\n}\n\n/**\n * Checks credentials and copies them, so later changes by the caller don't\n * reach the client.\n *\n * @param credentials - The credentials.\n * @returns The copy.\n * @throws PopSubError of kind `config` when they are neither a username and\n * password nor a token.\n */\nfunction checkCredentials(credentials: unknown): Credentials {\n if (typeof credentials !== \"object\" || credentials === null) {\n throw invalid(\"credentials are required\");\n }\n const fields = credentials as Record<string, unknown>;\n const { token, username, password } = fields;\n if (\"token\" in fields) {\n if (typeof token !== \"string\" || token === \"\") {\n throw invalid(\"the token must be a non-empty string\");\n }\n return { token };\n }\n if (typeof username !== \"string\" || typeof password !== \"string\") {\n throw invalid(\"credentials need a username and password, or a token\");\n }\n return { username, password };\n}\n\n/**\n * Fills in defaults and checks every setting.\n *\n * @param config - The configuration from the application.\n * @returns The complete configuration.\n * @throws PopSubError of kind `config` for a URL that isn't `ws://` or\n * `wss://`, credentials that are neither a password nor a token, a\n * session id outside 1 to 128 characters, or a timeout, delay or buffer\n * size that isn't positive.\n */\nexport function resolveConfig(config: ClientConfig): ResolvedConfig {\n const raw: unknown = config;\n if (typeof raw !== \"object\" || raw === null) {\n throw invalid(\"a configuration object is required\");\n }\n if (typeof config.url !== \"string\" || !/^wss?:\\/\\//i.test(config.url)) {\n throw invalid(\"url must start with ws:// or wss://\");\n }\n const sessionId = config.sessionId ?? null;\n if (\n sessionId !== null &&\n (typeof sessionId !== \"string\" || sessionId.length < 1 || sessionId.length > 128)\n ) {\n throw invalid(\"sessionId must be 1 to 128 characters\");\n }\n const ackMode: unknown = config.ackMode ?? \"auto\";\n if (ackMode !== \"auto\" && ackMode !== \"manual\") {\n throw invalid(\"ackMode must be auto or manual\");\n }\n const reconnect = { ...DEFAULT_RECONNECT, ...config.reconnect };\n positive(\"reconnect.initialMs\", reconnect.initialMs);\n positive(\"reconnect.maxMs\", reconnect.maxMs);\n if (\n reconnect.maxAttempts !== null &&\n (!Number.isInteger(reconnect.maxAttempts) || reconnect.maxAttempts < 0)\n ) {\n throw invalid(\"reconnect.maxAttempts must be a whole number of at least 0, or null\");\n }\n const subscriptionBuffer = config.subscriptionBuffer ?? DEFAULT_SUBSCRIPTION_BUFFER;\n if (!Number.isInteger(subscriptionBuffer) || subscriptionBuffer < 1) {\n throw invalid(\"subscriptionBuffer must be a whole number of at least 1\");\n }\n return {\n url: config.url,\n credentials: checkCredentials(config.credentials),\n sessionId,\n cleanStart: config.cleanStart ?? false,\n ackMode,\n reconnect,\n requestTimeoutMs: positive(\"requestTimeoutMs\", config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),\n subscriptionBuffer,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAmH1C,yEAAyE;AACzE,MAAM,CAAC,MAAM,iBAAiB,GA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;IACD,MAAM,SAAS,GAAG,EAAE,GAAG,iBAAiB,EAAE,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;IAChE,QAAQ,CAAC,qBAAqB,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;IACrD,QAAQ,CAAC,iBAAiB,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC;IAC7C,IACE,SAAS,CAAC,WAAW,KAAK,IAAI;QAC9B,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,SAAS,CAAC,WAAW,CAAC,IAAI,SAAS,CAAC,WAAW,GAAG,CAAC,CAAC,EACvE,CAAC;QACD,MAAM,OAAO,CAAC,qEAAqE,CAAC,CAAC;IACvF,CAAC;IACD,MAAM,kBAAkB,GAAG,MAAM,CAAC,kBAAkB,IAAI,2BAA2B,CAAC;IACpF,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,kBAAkB,CAAC,IAAI,kBAAkB,GAAG,CAAC,EAAE,CAAC;QACpE,MAAM,OAAO,CAAC,yDAAyD,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO;QACL,GAAG,EAAE,MAAM,CAAC,GAAG;QACf,WAAW,EAAE,gBAAgB,CAAC,MAAM,CAAC,WAAW,CAAC;QACjD,SAAS;QACT,UAAU,EAAE,MAAM,CAAC,UAAU,IAAI,KAAK;QACtC,OAAO;QACP,SAAS;QACT,gBAAgB,EAAE,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC,gBAAgB,IAAI,0BAA0B,CAAC;QACrG,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["/**\n * How a `Client` connects: where, as whom, and how it behaves when things\n * go wrong. `resolveConfig` fills in defaults and rejects invalid values.\n *\n * @module\n */\n\nimport { PopSubError } from \"./errors.js\";\n\n/**\n * A username and password. The client logs in on every connection and\n * refreshes its token on its own before it expires.\n */\nexport interface PasswordCredentials {\n /** The username. */\n username: string;\n /** The password. */\n password: string;\n}\n\n/**\n * A JWT obtained elsewhere. The client can't refresh it: when it expires\n * the server closes the connection with `token_expired` and the client\n * stops, after an `authExpiring` event.\n */\nexport interface TokenCredentials {\n /** The token. */\n token: string;\n}\n\n/**\n * A function that fetches a fresh token, such as from your backend, which\n * signs short-lived tokens for its signed-in users. The client calls it on\n * every connection, when the server warns the token is about to expire, and\n * to reconnect after it did expire. A rejection is retried like a failed\n * connection.\n */\nexport interface ProviderCredentials {\n /** Returns a fresh token. */\n tokenProvider: () => Promise<string>;\n}\n\n/** How the client proves who it is. */\nexport type Credentials = PasswordCredentials | TokenCredentials | ProviderCredentials;\n\n/**\n * When QoS 1 messages are acknowledged.\n *\n * - `auto`: as the client hands them to the subscription's buffer (or, when\n * the buffer is full, as the application takes them). A message the\n * application was processing when it crashed isn't redelivered.\n * - `manual`: when the application calls `Message.ack`. A message never\n * acknowledged is redelivered after a reconnect (to a durable session),\n * and stalls its subscription once the server runs out of retries.\n */\nexport type AckMode = \"auto\" | \"manual\";\n\n/**\n * How the client waits between reconnection attempts: a random wait\n * between zero and a ceiling that doubles from `initialMs` up to `maxMs`.\n */\nexport interface ReconnectPolicy {\n /** The starting ceiling, in milliseconds. */\n initialMs: number;\n /** The highest ceiling, in milliseconds. */\n maxMs: number;\n /** Give up after this many failed attempts in a row; `null` keeps trying. */\n maxAttempts: number | null;\n}\n\n/** Everything a `Client` needs to connect. Only `url` and `credentials` are required. */\nexport interface ClientConfig {\n /** The server's WebSocket URL, such as `ws://127.0.0.1:8080`, or `wss://` for TLS. */\n url: string;\n /** Who to connect as. */\n credentials: Credentials;\n /**\n * A durable session to hold, 1 to 128 characters, so subscriptions and\n * unacknowledged messages survive disconnects. Absent or `null` is an\n * ephemeral connection.\n */\n sessionId?: string | null;\n /** Discard the session's stored subscriptions on the first connection. Never sent on reconnects. */\n cleanStart?: boolean;\n /** When QoS 1 messages are acknowledged; `auto` by default. */\n ackMode?: AckMode;\n /** How to reconnect; 250 ms doubling up to 30 seconds, forever, by default. */\n reconnect?: Partial<ReconnectPolicy>;\n /**\n * How long a request (connect, subscribe, unsubscribe, confirmed publish,\n * admin call) may take, reconnects included, in milliseconds; 30 seconds\n * by default.\n */\n requestTimeoutMs?: number;\n /**\n * How many messages each subscription buffers for the application before\n * the client starts holding back; 1024 by default. See the README's\n * section on backpressure for what happens beyond it.\n */\n subscriptionBuffer?: number;\n}\n\n/** A `ClientConfig` with every default filled in. */\nexport interface ResolvedConfig {\n /** The server's WebSocket URL. */\n url: string;\n /** Who to connect as. */\n credentials: Credentials;\n /** The durable session, or `null` for an ephemeral connection. */\n sessionId: string | null;\n /** Whether the first connection discards the session's stored subscriptions. */\n cleanStart: boolean;\n /** When QoS 1 messages are acknowledged. */\n ackMode: AckMode;\n /** How to reconnect. */\n reconnect: ReconnectPolicy;\n /** How long a request may take, in milliseconds. */\n requestTimeoutMs: number;\n /** How many messages each subscription buffers before holding back. */\n subscriptionBuffer: number;\n}\n\n/** The reconnect policy used for fields the configuration leaves out. */\nexport const DEFAULT_RECONNECT: Readonly<ReconnectPolicy> = Object.freeze({\n initialMs: 250,\n maxMs: 30_000,\n maxAttempts: null,\n});\n\n/** The request timeout used when the configuration leaves it out. */\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;\n\n/** The subscription buffer size used when the configuration leaves it out. */\nexport const DEFAULT_SUBSCRIPTION_BUFFER = 1024;\n\n/**\n * Builds the error for an invalid setting.\n *\n * @param message - What is wrong.\n * @returns The `config` error.\n */\nfunction invalid(message: string): PopSubError {\n return new PopSubError(\"config\", `invalid configuration: ${message}`);\n}\n\n/**\n * Checks that a setting is a positive, finite number.\n *\n * @param name - The setting's name, for the error.\n * @param value - Its value.\n * @returns The value.\n * @throws PopSubError of kind `config` when it isn't.\n */\nfunction positive(name: string, value: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw invalid(`${name} must be a positive number`);\n }\n return value;\n}\n\n/**\n * Checks credentials and copies them, so later changes by the caller don't\n * reach the client.\n *\n * @param credentials - The credentials.\n * @returns The copy.\n * @throws PopSubError of kind `config` when they are neither a username and\n * password, a token, nor a token provider.\n */\nfunction checkCredentials(credentials: unknown): Credentials {\n if (typeof credentials !== \"object\" || credentials === null) {\n throw invalid(\"credentials are required\");\n }\n const fields = credentials as Record<string, unknown>;\n const { token, username, password, tokenProvider } = fields;\n if (\"tokenProvider\" in fields) {\n if (typeof tokenProvider !== \"function\") {\n throw invalid(\"the token provider must be a function\");\n }\n return { tokenProvider: tokenProvider as () => Promise<string> };\n }\n if (\"token\" in fields) {\n if (typeof token !== \"string\" || token === \"\") {\n throw invalid(\"the token must be a non-empty string\");\n }\n return { token };\n }\n if (typeof username !== \"string\" || typeof password !== \"string\") {\n throw invalid(\"credentials need a username and password, a token, or a token provider\");\n }\n return { username, password };\n}\n\n/**\n * Fills in defaults and checks every setting.\n *\n * @param config - The configuration from the application.\n * @returns The complete configuration.\n * @throws PopSubError of kind `config` for a URL that isn't `ws://` or\n * `wss://`, credentials that are neither a password nor a token, a\n * session id outside 1 to 128 characters, or a timeout, delay or buffer\n * size that isn't positive.\n */\nexport function resolveConfig(config: ClientConfig): ResolvedConfig {\n const raw: unknown = config;\n if (typeof raw !== \"object\" || raw === null) {\n throw invalid(\"a configuration object is required\");\n }\n if (typeof config.url !== \"string\" || !/^wss?:\\/\\//i.test(config.url)) {\n throw invalid(\"url must start with ws:// or wss://\");\n }\n const sessionId = config.sessionId ?? null;\n if (\n sessionId !== null &&\n (typeof sessionId !== \"string\" || sessionId.length < 1 || sessionId.length > 128)\n ) {\n throw invalid(\"sessionId must be 1 to 128 characters\");\n }\n const ackMode: unknown = config.ackMode ?? \"auto\";\n if (ackMode !== \"auto\" && ackMode !== \"manual\") {\n throw invalid(\"ackMode must be auto or manual\");\n }\n const reconnect = { ...DEFAULT_RECONNECT, ...config.reconnect };\n positive(\"reconnect.initialMs\", reconnect.initialMs);\n positive(\"reconnect.maxMs\", reconnect.maxMs);\n if (\n reconnect.maxAttempts !== null &&\n (!Number.isInteger(reconnect.maxAttempts) || reconnect.maxAttempts < 0)\n ) {\n throw invalid(\"reconnect.maxAttempts must be a whole number of at least 0, or null\");\n }\n const subscriptionBuffer = config.subscriptionBuffer ?? DEFAULT_SUBSCRIPTION_BUFFER;\n if (!Number.isInteger(subscriptionBuffer) || subscriptionBuffer < 1) {\n throw invalid(\"subscriptionBuffer must be a whole number of at least 1\");\n }\n return {\n url: config.url,\n credentials: checkCredentials(config.credentials),\n sessionId,\n cleanStart: config.cleanStart ?? false,\n ackMode,\n reconnect,\n requestTimeoutMs: positive(\"requestTimeoutMs\", config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS),\n subscriptionBuffer,\n };\n}\n"]}
|
package/dist/engine.d.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* it ends. The close code decides what happens next: reconnect with
|
|
7
7
|
* jittered backoff, or stop for good (`session_taken_over`,
|
|
8
8
|
* `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected
|
|
9
|
-
* credentials, and `token_expired` with token
|
|
9
|
+
* credentials, and `token_expired` with a fixed token). After
|
|
10
10
|
* reconnecting it resubscribes every topic from the next `seq` it expects
|
|
11
11
|
* (a topic the server lists as resumed for a durable session is instead
|
|
12
12
|
* subscribed again from `resume` when the server holds the session's
|
package/dist/engine.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* it ends. The close code decides what happens next: reconnect with
|
|
7
7
|
* jittered backoff, or stop for good (`session_taken_over`,
|
|
8
8
|
* `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected
|
|
9
|
-
* credentials, and `token_expired` with token
|
|
9
|
+
* credentials, and `token_expired` with a fixed token). After
|
|
10
10
|
* reconnecting it resubscribes every topic from the next `seq` it expects
|
|
11
11
|
* (a topic the server lists as resumed for a durable session is instead
|
|
12
12
|
* subscribed again from `resume` when the server holds the session's
|
|
@@ -498,14 +498,16 @@ export class Engine {
|
|
|
498
498
|
*
|
|
499
499
|
* @param code - The server's close code, if it sent one.
|
|
500
500
|
* @returns True to reconnect. An expired token only allows it with
|
|
501
|
-
* password credentials, which log in again
|
|
501
|
+
* password credentials, which log in again, or a token provider, which
|
|
502
|
+
* fetches a fresh token.
|
|
502
503
|
*/
|
|
503
504
|
#shouldReconnect(code) {
|
|
504
505
|
if (code === null) {
|
|
505
506
|
return true;
|
|
506
507
|
}
|
|
507
508
|
if (code === 4004) {
|
|
508
|
-
|
|
509
|
+
const credentials = this.#config.credentials;
|
|
510
|
+
return "password" in credentials || "tokenProvider" in credentials;
|
|
509
511
|
}
|
|
510
512
|
return shouldReconnect(code);
|
|
511
513
|
}
|
|
@@ -588,6 +590,9 @@ export class Engine {
|
|
|
588
590
|
if ("token" in credentials) {
|
|
589
591
|
token = credentials.token;
|
|
590
592
|
}
|
|
593
|
+
else if ("tokenProvider" in credentials) {
|
|
594
|
+
token = await fetchToken(credentials.tokenProvider);
|
|
595
|
+
}
|
|
591
596
|
else {
|
|
592
597
|
const reply = await handshake.exchange(this.#takeId(), {
|
|
593
598
|
type: "login",
|
|
@@ -815,6 +820,26 @@ export class Engine {
|
|
|
815
820
|
}
|
|
816
821
|
socket.send(encodeFrame(message, id));
|
|
817
822
|
}
|
|
823
|
+
/**
|
|
824
|
+
* Fetches a fresh token from the provider and sends it as a repeat `auth`
|
|
825
|
+
* on the connection that asked, which refreshes its token. If that
|
|
826
|
+
* connection has ended by the time the token arrives, it is dropped: a new
|
|
827
|
+
* connection fetched its own. A failed fetch is left for the connection
|
|
828
|
+
* to close when its token expires, and reconnecting fetches again.
|
|
829
|
+
*
|
|
830
|
+
* @param provider - The token provider.
|
|
831
|
+
*/
|
|
832
|
+
#renew(provider) {
|
|
833
|
+
const connection = this.#connection;
|
|
834
|
+
fetchToken(provider).then((token) => {
|
|
835
|
+
if (this.#connection !== connection) {
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
const authId = this.#takeId();
|
|
839
|
+
this.#pending.set(authId, { kind: "reauth" });
|
|
840
|
+
this.#send({ type: "auth", token, protocol: PROTOCOL_VERSION }, authId);
|
|
841
|
+
}, () => undefined);
|
|
842
|
+
}
|
|
818
843
|
/**
|
|
819
844
|
* Takes a request id.
|
|
820
845
|
*
|
|
@@ -1100,6 +1125,9 @@ export class Engine {
|
|
|
1100
1125
|
const { username, password } = this.#config.credentials;
|
|
1101
1126
|
this.#send({ type: "login", username, password }, loginId);
|
|
1102
1127
|
}
|
|
1128
|
+
else if ("tokenProvider" in this.#config.credentials) {
|
|
1129
|
+
this.#renew(this.#config.credentials.tokenProvider);
|
|
1130
|
+
}
|
|
1103
1131
|
break;
|
|
1104
1132
|
case "logged_in":
|
|
1105
1133
|
if (pending?.kind === "relogin") {
|
|
@@ -1303,4 +1331,26 @@ export class Engine {
|
|
|
1303
1331
|
this.#finish();
|
|
1304
1332
|
}
|
|
1305
1333
|
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Calls a token provider and checks what it returns.
|
|
1336
|
+
*
|
|
1337
|
+
* @param provider - The token provider.
|
|
1338
|
+
* @returns The token.
|
|
1339
|
+
* @throws PopSubError of kind `connect` when the provider rejects or returns
|
|
1340
|
+
* something other than a non-empty string, so the attempt is retried.
|
|
1341
|
+
*/
|
|
1342
|
+
async function fetchToken(provider) {
|
|
1343
|
+
let token;
|
|
1344
|
+
try {
|
|
1345
|
+
token = await provider();
|
|
1346
|
+
}
|
|
1347
|
+
catch (error) {
|
|
1348
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1349
|
+
throw new PopSubError("connect", `the token provider failed: ${message}`, { cause: error });
|
|
1350
|
+
}
|
|
1351
|
+
if (typeof token !== "string" || token === "") {
|
|
1352
|
+
throw new PopSubError("connect", "the token provider returned no token");
|
|
1353
|
+
}
|
|
1354
|
+
return token;
|
|
1355
|
+
}
|
|
1306
1356
|
//# sourceMappingURL=engine.js.map
|
package/dist/engine.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;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I,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC;YAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF","sourcesContent":["/**\n * The engine behind a `Client`: it owns the WebSocket and does what every\n * application would otherwise have to.\n *\n * It connects, logs in and authenticates, then serves the connection until\n * it ends. The close code decides what happens next: reconnect with\n * jittered backoff, or stop for good (`session_taken_over`,\n * `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected\n * credentials, and `token_expired` with token credentials). After\n * reconnecting it resubscribes every topic from the next `seq` it expects\n * (a topic the server lists as resumed for a durable session is instead\n * subscribed again from `resume` when the server holds the session's\n * topics, and otherwise left to the server unless a claim on it is still\n * unanswered; see below), resends confirmed publishes that never got their `published` under the\n * same request id and `message_id`, and sends QoS 0 publishes and\n * unsubscribes queued while disconnected.\n *\n * Every message is checked against the next `seq` its topic expects, so a\n * retry or a replay never reaches the application twice. A duplicate the\n * application acknowledged before (or any duplicate in automatic mode,\n * unless its acknowledgement is held back for a full buffer) is\n * acknowledged again, so a lost acknowledgement can't stall the topic.\n *\n * A durable session outlives the process. When a new process connects\n * with the same session id, the server lists the session's topics in\n * `authenticated.resumed` before the application has subscribed to\n * anything. The engine must never acknowledge a message the application\n * couldn't have received, so with a session id its `auth` carries\n * `hold_resumed: true`. A server that honours it answers `held: true` and\n * sends nothing on a resumed topic until the engine subscribes to it. Then\n * nothing is unclaimed, a subscribe to a resumed topic is an ordinary\n * subscribe, a pattern needs no subscribes by name, and after a reconnect\n * the engine subscribes again to every tracked topic the server lists as\n * resumed, with `from: \"resume\"`, because the server no longer does it.\n *\n * A server that doesn't know `hold_resumed` answers without `held` and\n * sends what it kept for the resumed topics at once. A resumed topic the engine\n * isn't tracking is unclaimed: its messages are dropped without an\n * acknowledgement, so the server keeps them for the session. Subscribing\n * to an unclaimed topic by name, or to a pattern that matches it, claims\n * it. A claimed topic is tracked, but its messages are still dropped\n * unacknowledged until the `subscribed` that answers the claim arrives,\n * because the subscribe replays them in order from `replay_from`. A\n * pattern claims a topic by sending one more `subscribe` for it by name\n * with `from: \"resume\"`, since the server skips topics the connection\n * holds when it handles the pattern itself. After a reconnect a claim\n * still unanswered is sent again even when the server lists the topic as\n * resumed. A topic the application never subscribes to stays unclaimed.\n *\n * A wildcard subscription (`orders/#`) is one pattern with one channel.\n * The server announces each topic it joins for the pattern with a\n * `subscribed` frame that has no id; the engine then tracks that topic\n * like any other, with its own next expected `seq` and acknowledgement\n * memory, owned by the pattern and feeding the pattern's channel. A\n * `subscribed` or `message` for an untracked topic is matched against the\n * patterns, and the oldest matching one owns it. After a reconnect the\n * tracked topics are resubscribed first, then each pattern is sent again\n * with `from: {\"seq\": 1}`, which joins only topics created meanwhile.\n * Subscribing again to a pattern the engine holds replaces the\n * subscription: the topics it owned move to the new channel and keep\n * their next expected `seq`, because the server sends nothing again for\n * topics the connection holds, and the earlier channel ends.\n *\n * A shared subscription (a topic read through a `group`) gets only some of\n * the topic's messages, out of order, so duplicates are found with a\n * bounded set of delivered `seq`s instead of a next expected one, nothing\n * moves on `subscribed.replay_from` or `truncated`, and after a reconnect\n * it always rejoins the group with `from: \"resume\"`.\n *\n * An `unsubscribed` frame with no id means the server ended the\n * subscription; every unsubscribe the engine sends carries an id so its\n * reply is never mistaken for that.\n *\n * The browser `WebSocket` API can't pause reading, so backpressure works in\n * two steps. While a subscription's buffer holds `subscriptionBuffer`\n * messages or more, automatic acknowledgements of new QoS 1 messages wait\n * until the application takes them; the server's per-subscription window\n * (`limits.max_inflight`) then stops sending to it, QoS 0 included. If the\n * buffer still reaches `subscriptionBuffer + max_inflight` (possible with\n * QoS 0 traffic, which no window paces), the engine drops the connection,\n * waits until the application has taken that buffer down to half of\n * `subscriptionBuffer`, reconnects, and resubscribes that topic from the\n * next `seq` it expects, so the log fills the gap. Memory per subscription\n * stays below `subscriptionBuffer + max_inflight` messages.\n *\n * Nor does the API show the server's WebSocket pings, so silence is\n * detected with the protocol's own `ping` request: after `heartbeat_secs`\n * with nothing from the server the engine sends `ping` with an id, and\n * again after each further `heartbeat_secs` of silence. Any frame,\n * including the `pong` reply, counts as hearing from the server. Once\n * `idle_timeout_secs + heartbeat_secs` pass with nothing at all, the\n * connection is given up and the engine reconnects.\n *\n * @module\n */\n\nimport { jitteredDelay } from \"./backoff.js\";\nimport type { ResolvedConfig } from \"./config.js\";\nimport { ACK_MEMORY, DeliveryTracker } from \"./dedup.js\";\nimport { Emitter } from \"./events.js\";\nimport { PopSubError } from \"./errors.js\";\nimport { Aborted, ConnectFailure, Handshake } from \"./handshake.js\";\nimport { isPattern, matchesPattern } from \"./pattern.js\";\nimport {\n closeCode,\n encodeFrame,\n errorCode,\n parseServerFrame,\n PROTOCOL_VERSION,\n publishFrame,\n shouldReconnect,\n type ClientMessage,\n type CloseCode,\n type Encoding,\n type Limits,\n type ServerFrame,\n type ServerMessage,\n type WireStartFrom,\n} from \"./protocol.js\";\nimport { Channel, Message, Subscription } from \"./subscription.js\";\n\n/** How many QoS 0 publishes and unsubscribes are held while disconnected; the oldest go first. */\nexport const OFFLINE_LIMIT = 10_000;\n\n/** How long to wait for anything from the server before the server has announced its limits. */\nconst DEFAULT_SILENCE_MS = 120_000;\n\n/** How long a connection may be silent before a `ping`, before the server has announced its limits. */\nconst DEFAULT_PING_MS = 30_000;\n\n/** The window size assumed before the server has announced its limits. */\nconst DEFAULT_MAX_INFLIGHT = 100;\n\n/** The result of a confirmed publish. */\nexport interface Published {\n /** The message's position in the topic. */\n seq: number;\n /** The id it was stored under. */\n messageId: string;\n}\n\n/** How to settle a caller's promise. */\ninterface Settle<T> {\n /** Fulfils it. */\n resolve(value: T): void;\n /** Rejects it. */\n reject(error: PopSubError): void;\n}\n\n/** A request waiting for its reply, by request id. */\ntype Pending =\n | { kind: \"subscribe\"; topic: string; generation: number }\n | { kind: \"unsubscribe\"; settle: Settle<void> }\n | { kind: \"publish\"; settle: Settle<Published> }\n | { kind: \"request\"; settle: Settle<ServerMessage> }\n | { kind: \"relogin\" }\n | { kind: \"reauth\" }\n | { kind: \"ping\" };\n\n/** One subscribed topic. */\ninterface Topic {\n /** Where its messages go. */\n channel: Channel;\n /** Where replay started when the application subscribed. */\n from: WireStartFrom;\n /** Which subscription this is, so a stale close can't remove a newer one. */\n generation: number;\n /** The next expected `seq` and acknowledgement memory. */\n tracker: DeliveryTracker;\n /** Whether its buffer overflowed, so deliveries are dropped until it is resubscribed. */\n overflowed: boolean;\n /** The wildcard pattern it was joined through, or `null` when subscribed by name. */\n owner: string | null;\n /** The shared subscription's group, or `null` for an ordinary subscription. */\n group: string | null;\n /**\n * Whether the server held this topic for the session before the\n * application subscribed, and the `subscribed` that answers the\n * application's subscribe hasn't arrived yet. Until it does, messages on\n * the topic are the server's own resume: they are dropped without an\n * acknowledgement, because the subscribe replays them.\n */\n claiming: boolean;\n}\n\n/** One wildcard subscription. */\ninterface Pattern {\n /** Where the messages of every topic it owns go. */\n channel: Channel;\n /** Which subscription this is; the oldest matching pattern owns a new topic. */\n generation: number;\n}\n\n/** How a served connection ended. */\ntype Ending = { kind: \"stop\" } | { kind: \"lost\"; code: CloseCode | null } | { kind: \"pause\" };\n\n/** The outcome of one connection attempt. */\ntype Attempt =\n | { kind: \"connected\"; handshake: Handshake; resumed: string[] }\n | { kind: \"failed\"; failure: ConnectFailure }\n | { kind: \"stopped\" };\n\n/**\n * Creates a version 4 UUID, with `crypto.randomUUID` where the runtime has\n * it (browsers only offer it on secure origins) and `getRandomValues`\n * otherwise.\n *\n * @returns The UUID.\n */\nexport function uuid(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * Turns an unexpected reply during connecting into a failure.\n *\n * @param reply - What the server sent instead of the expected reply.\n * @returns The failure; retryable only for the server's temporary refusals\n * and for replies of the wrong type.\n */\nfunction refusal(reply: ServerMessage): ConnectFailure {\n if (reply.type === \"error\") {\n const error = PopSubError.server(errorCode(reply.code), reply.message, reply.retry_after ?? null);\n return new ConnectFailure(error, error.isTemporary());\n }\n return new ConnectFailure(new PopSubError(\"protocol\", `unexpected ${reply.type} while connecting`), true);\n}\n\n/** The state and the run loop behind one `Client`. */\nexport class Engine {\n /** How to connect. */\n readonly #config: ResolvedConfig;\n /** Where events go. */\n readonly emitter = new Emitter();\n /** Subscribed topics. */\n readonly #topics = new Map<string, Topic>();\n /** Wildcard subscriptions, by pattern. */\n readonly #patterns = new Map<string, Pattern>();\n /**\n * Topics the server restored for the session that the application hasn't\n * subscribed to in this process. Their messages are dropped without an\n * acknowledgement, so the server keeps them for the session.\n */\n #unclaimed = new Set<string>();\n /**\n * Whether the server left the session's topics unattached on this\n * connection (`authenticated.held`). Then nothing arrives on a topic\n * until the engine subscribes to it, so nothing is unclaimed, and\n * `#restore` subscribes to the resumed topics itself.\n */\n #held = false;\n /** Subscribes waiting for `subscribed`, by topic. */\n readonly #subscribeWaiters = new Map<string, Settle<void>>();\n /** Requests waiting for a reply, by id. */\n readonly #pending = new Map<number, Pending>();\n /** Confirmed publishes not yet confirmed, by request id, in id order, for resending. */\n readonly #unconfirmed = new Map<number, ClientMessage>();\n /** QoS 0 publishes and unsubscribes to send once connected. */\n #offline: ClientMessage[] = [];\n /** The next request id. */\n #nextId = 1;\n /** The next subscription generation. */\n #nextGeneration = 1;\n /** Whether a connection has ever succeeded, so `clean_start` is only sent once. */\n #connectedOnce = false;\n /** How long to wait for anything from the server before giving up on the connection. */\n #silenceMs = DEFAULT_SILENCE_MS;\n /** How long a connection may be silent before a `ping`, and between `ping`s while it stays silent. */\n #pingMs = DEFAULT_PING_MS;\n /** The server's per-subscription window. */\n #maxInflight = DEFAULT_MAX_INFLIGHT;\n /** The served connection, while there is one. */\n #connection: Handshake | null = null;\n /** Ends the served connection, while there is one. */\n #endServe: ((ending: Ending) => void) | null = null;\n /** Re-checks whatever the run loop is waiting for; set by each wait. */\n #wake: (() => void) | null = null;\n /** Whether the application asked to close. */\n #closing = false;\n /** Why the client stopped, once it has. */\n #stopped: { code: CloseCode | null } | null = null;\n /** Settles when the first connection is up, or rejects with what stopped the client first. */\n readonly ready: Promise<void>;\n /** Settles `ready`. */\n #ready: Settle<void> | null = null;\n /** Settles when the run loop has finished and the client has stopped. */\n readonly finished: Promise<void>;\n /** Settles `finished`. */\n #finish: () => void = () => undefined;\n\n /**\n * Builds an engine and starts its run loop.\n *\n * @param config - How to connect.\n */\n constructor(config: ResolvedConfig) {\n this.#config = config;\n this.ready = new Promise<void>((resolve, reject) => {\n this.#ready = { resolve, reject };\n });\n this.ready.catch(() => undefined);\n this.finished = new Promise<void>((resolve) => {\n this.#finish = resolve;\n });\n void this.#run();\n }\n\n /**\n * Why the client stopped, if it has.\n *\n * @returns `{ code }` once stopped (the code is `null` when the\n * application closed it or it ran out of attempts), `null` while running.\n */\n get stopped(): { code: CloseCode | null } | null {\n return this.#stopped;\n }\n\n /**\n * Subscribes to a topic or a wildcard pattern, replacing any earlier\n * subscription to the same name. With a group it joins a shared\n * subscription to the topic.\n *\n * Subscribing again to a topic by name starts over from `from`.\n * Subscribing again to a pattern keeps the topics it owned (see\n * `#replacePattern`).\n *\n * A topic the server held for the session, subscribed by name or matched\n * by the pattern, is claimed: it is tracked with `claiming` set, so what\n * the server sent on its own is dropped until the `subscribed` that\n * answers the claim. A topic subscribed again while its claim is\n * unanswered stays `claiming`. For a pattern each claimed topic gets its own\n * subscribe by name with `from: \"resume\"`, sent after the pattern's.\n * While disconnected nothing is sent; `#restore` sends the claims on the\n * next connection.\n *\n * @param topic - The topic, or a pattern such as `orders/#`.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n * @returns The subscription, and a promise that settles when the server\n * confirms it.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n subscribe(\n topic: string,\n from: WireStartFrom,\n group: string | null = null,\n ): { subscription: Subscription; done: Promise<void> } {\n this.#throwIfStopped();\n const generation = this.#nextGeneration++;\n const channel = new Channel(topic, {\n taken: (message) => {\n this.#taken(message.topic, generation, message);\n },\n leave: () => {\n this.#forget(topic, generation);\n },\n });\n const wildcard = group === null && isPattern(topic);\n const stillClaiming = this.#topics.get(topic)?.claiming === true;\n if (wildcard && this.#patterns.has(topic)) {\n this.#replacePattern(topic, channel, generation);\n } else {\n this.#release(topic, null);\n }\n this.#subscribeWaiters\n .get(topic)\n ?.reject(new PopSubError(\"protocol\", `replaced by a later subscribe to '${topic}'`));\n let claimed: string[] = [];\n if (wildcard) {\n this.#patterns.set(topic, { channel, generation });\n claimed = this.#claimMatching(topic, channel, generation);\n } else {\n this.#topics.set(topic, {\n channel,\n from,\n generation,\n tracker: new DeliveryTracker(ACK_MEMORY, group !== null),\n overflowed: false,\n owner: null,\n group,\n claiming: this.#unclaimed.delete(topic) || stillClaiming,\n });\n }\n const done = new Promise<void>((resolve, reject) => {\n this.#subscribeWaiters.set(topic, { resolve, reject });\n });\n if (this.#connection !== null) {\n this.#sendSubscribe(topic, generation, from, group);\n for (const name of claimed) {\n this.#sendSubscribe(name, generation, \"resume\", null);\n }\n }\n return { subscription: new Subscription(channel), done };\n }\n\n /**\n * Unsubscribes from a topic, or from a pattern and every topic joined\n * through it. While disconnected the unsubscribes are queued and the\n * call succeeds at once.\n *\n * @param topic - The topic or pattern.\n * @returns A promise that settles with the server's reply to the\n * unsubscribe for `topic` itself.\n */\n unsubscribe(topic: string): Promise<void> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n const released = this.#release(topic, null);\n const [first, ...owned] = released.length === 0 ? [topic] : released;\n if (this.#connection === null) {\n for (const name of [first ?? topic, ...owned]) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n }\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"unsubscribe\", settle: { resolve, reject } });\n this.#send({ type: \"unsubscribe\", topic: first ?? topic }, id);\n for (const name of owned) {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n });\n }\n\n /**\n * Publishes at QoS 0. While disconnected the publish is queued.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n publish(topic: string, payload: string, encoding: Encoding | null = null): void {\n this.#throwIfStopped();\n this.#queueOffline(publishFrame(topic, payload, encoding));\n this.#flushOffline();\n }\n\n /**\n * Publishes at QoS 1 under a new `message_id`, resending it after every\n * reconnect until the server confirms it.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @returns A promise that settles with the `seq` and id once stored.\n */\n publishConfirmed(topic: string, payload: string, encoding: Encoding | null = null): Promise<Published> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n return new Promise<Published>((resolve, reject) => {\n const id = this.#takeId();\n const message: ClientMessage = {\n ...publishFrame(topic, payload, encoding),\n message_id: uuid(),\n qos: 1,\n };\n this.#pending.set(id, { kind: \"publish\", settle: { resolve, reject } });\n this.#unconfirmed.set(id, message);\n if (this.#connection !== null) {\n this.#send(message, id);\n }\n });\n }\n\n /**\n * Acknowledges a message (from `Message.ack`). While disconnected it is\n * only remembered, so a redelivery is acknowledged again.\n *\n * @param topic - The topic.\n * @param seq - The message's `seq`.\n */\n ack(topic: string, seq: number): void {\n this.#topics.get(topic)?.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic, seq });\n }\n\n /**\n * Sends a request that is never queued while disconnected and never\n * resent (the admin requests), and returns its reply.\n *\n * @param message - The request.\n * @returns A promise that settles with the reply, rejecting with a\n * `server` error for an `error` frame, or `connect` when disconnected\n * or when the connection drops first.\n */\n request(message: ClientMessage): Promise<ServerMessage> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n if (this.#connection === null) {\n return Promise.reject(\n new PopSubError(\"connect\", \"not connected; this request isn't queued while disconnected\"),\n );\n }\n return new Promise<ServerMessage>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"request\", settle: { resolve, reject } });\n this.#send(message, id);\n });\n }\n\n /**\n * Closes the connection and stops the client. Pending requests fail with\n * a `closed` error.\n *\n * @returns A promise that settles once the client has stopped.\n */\n close(): Promise<void> {\n if (this.#stopped === null) {\n this.#closing = true;\n this.#wake?.();\n }\n return this.finished;\n }\n\n /**\n * Runs until the client stops, then stops it. An unexpected exception\n * stops the client too, and becomes the cause of the error `ready`\n * rejects with, so the returned promise never rejects.\n */\n async #run(): Promise<void> {\n try {\n this.#stop(await this.#loop());\n } catch (error) {\n this.#stop(null, error);\n }\n }\n\n /**\n * Connects, serves the connection, reconnects with backoff, and settles\n * `ready` with the first outcome, until the client must stop.\n *\n * @returns The close code that stopped the client, or `null` when the\n * application closed it, it ran out of attempts, or connecting failed\n * in a way retrying can't fix.\n */\n async #loop(): Promise<CloseCode | null> {\n let attempt = 0;\n let lastError: PopSubError | null = null;\n while (!this.#closing) {\n const outcome = await this.#connectOnce();\n if (outcome.kind === \"stopped\") {\n break;\n }\n if (outcome.kind === \"connected\") {\n attempt = 0;\n this.#connectedOnce = true;\n this.#ready?.resolve();\n this.#ready = null;\n this.emitter.emit({ type: \"connected\", resumed: outcome.resumed });\n const ending = await this.#serve(outcome.handshake, outcome.resumed);\n if (ending.kind === \"stop\") {\n break;\n }\n this.#failRequests();\n if (ending.kind === \"pause\") {\n this.emitter.emit({ type: \"disconnected\", code: null, reconnecting: true });\n if (!(await this.#waitForRoom())) {\n break;\n }\n continue;\n }\n const reconnecting = this.#shouldReconnect(ending.code);\n this.emitter.emit({ type: \"disconnected\", code: ending.code, reconnecting });\n if (!reconnecting) {\n return ending.code;\n }\n } else {\n lastError = outcome.failure.error;\n if (!outcome.failure.retry) {\n this.#ready?.reject(outcome.failure.error);\n this.#ready = null;\n break;\n }\n }\n attempt += 1;\n const maxAttempts = this.#config.reconnect.maxAttempts;\n if (maxAttempts !== null && attempt > maxAttempts) {\n const reason = lastError === null ? \"\" : `; the last attempt failed: ${lastError.message}`;\n this.#ready?.reject(\n new PopSubError(\"connect\", `ran out of reconnect attempts${reason}`, { cause: lastError }),\n );\n this.#ready = null;\n break;\n }\n if (!(await this.#sleep(jitteredDelay(this.#config.reconnect, attempt)))) {\n break;\n }\n }\n return null;\n }\n\n /**\n * Decides whether to reconnect after a connection was lost.\n *\n * @param code - The server's close code, if it sent one.\n * @returns True to reconnect. An expired token only allows it with\n * password credentials, which log in again.\n */\n #shouldReconnect(code: CloseCode | null): boolean {\n if (code === null) {\n return true;\n }\n if (code === 4004) {\n return \"password\" in this.#config.credentials;\n }\n return shouldReconnect(code);\n }\n\n /**\n * Waits before the next attempt, unless the application closes the client.\n *\n * @param ms - How long to wait.\n * @returns False when the application closed the client while waiting.\n */\n #sleep(ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (this.#closing) {\n resolve(false);\n return;\n }\n const timer = setTimeout(() => {\n this.#wake = null;\n resolve(true);\n }, ms);\n this.#wake = () => {\n if (this.#closing) {\n clearTimeout(timer);\n this.#wake = null;\n resolve(false);\n }\n };\n });\n }\n\n /**\n * After a buffer overflowed, waits until every overflowed topic's buffer\n * is down to half of `subscriptionBuffer` (or the topic is gone).\n *\n * @returns False when the application closed the client while waiting.\n */\n #waitForRoom(): Promise<boolean> {\n const low = Math.floor(this.#config.subscriptionBuffer / 2);\n const drained = (): boolean =>\n [...this.#topics.values()].every((topic) => !topic.overflowed || topic.channel.size <= low);\n return new Promise((resolve) => {\n const check = (): void => {\n if (this.#closing) {\n this.#wake = null;\n resolve(false);\n } else if (drained()) {\n this.#wake = null;\n resolve(true);\n }\n };\n this.#wake = check;\n check();\n });\n }\n\n /**\n * Opens a connection, logs in if needed, and authenticates. With a\n * session id the `auth` asks the server to hold the session's topics\n * (`hold_resumed`), and `#held` records whether it did.\n *\n * @returns The authenticated connection with the topics the server\n * restored, a failure saying whether retrying could help, or `stopped`\n * when the application closed the client meanwhile.\n */\n async #connectOnce(): Promise<Attempt> {\n let handshake: Handshake;\n try {\n handshake = new Handshake(this.#config.url, this.#config.requestTimeoutMs);\n } catch (error) {\n const failure =\n error instanceof PopSubError ? error : new PopSubError(\"config\", String(error), { cause: error });\n return { kind: \"failed\", failure: new ConnectFailure(failure, false) };\n }\n this.#wake = () => {\n if (this.#closing) {\n handshake.abort();\n }\n };\n try {\n await handshake.opened();\n const credentials = this.#config.credentials;\n let token: string;\n if (\"token\" in credentials) {\n token = credentials.token;\n } else {\n const reply = await handshake.exchange(this.#takeId(), {\n type: \"login\",\n username: credentials.username,\n password: credentials.password,\n });\n if (reply.type !== \"logged_in\") {\n throw refusal(reply);\n }\n token = reply.token;\n }\n const auth: ClientMessage = { type: \"auth\", token, protocol: PROTOCOL_VERSION };\n if (this.#config.sessionId !== null) {\n auth.session_id = this.#config.sessionId;\n auth.hold_resumed = true;\n }\n if (this.#config.cleanStart && !this.#connectedOnce) {\n auth.clean_start = true;\n }\n const reply = await handshake.exchange(this.#takeId(), auth);\n if (reply.type !== \"authenticated\") {\n throw refusal(reply);\n }\n this.#applyLimits(reply.limits);\n this.#held = reply.held === true;\n return { kind: \"connected\", handshake, resumed: reply.resumed ?? [] };\n } catch (reason) {\n handshake.close();\n if (reason instanceof Aborted) {\n return { kind: \"stopped\" };\n }\n if (reason instanceof ConnectFailure) {\n return { kind: \"failed\", failure: reason };\n }\n const message = reason instanceof Error ? reason.message : String(reason);\n return {\n kind: \"failed\",\n failure: new ConnectFailure(new PopSubError(\"connect\", message, { cause: reason }), true),\n };\n } finally {\n this.#wake = null;\n }\n }\n\n /**\n * Reads the server's limits: when to `ping`, how much silence to allow,\n * and the window size.\n *\n * @param limits - The limits from `authenticated`.\n */\n #applyLimits(limits: Limits): void {\n const idle = Math.max(1, limits.idle_timeout_secs);\n const heartbeat = Math.max(1, limits.heartbeat_secs);\n this.#pingMs = heartbeat * 1000;\n this.#silenceMs = (idle + heartbeat) * 1000;\n if (Number.isFinite(limits.max_inflight) && limits.max_inflight > 0) {\n this.#maxInflight = limits.max_inflight;\n }\n }\n\n /**\n * Serves one connection until it ends. Works out which restored topics\n * are unclaimed (those the engine isn't tracking, or none when the server\n * holds the session's topics), restores subscriptions\n * and resends, then handles frames as they arrive. A timer sends `ping` while\n * the connection is silent and ends it as lost once the silence passes\n * `idle_timeout_secs + heartbeat_secs`.\n *\n * @param handshake - The authenticated connection.\n * @param resumed - Topics the server restored for the session.\n * @returns How the connection ended.\n */\n #serve(handshake: Handshake, resumed: string[]): Promise<Ending> {\n return new Promise<Ending>((resolve) => {\n let lastHeard = Date.now();\n let lastPing = lastHeard;\n const tick = Math.max(50, Math.min(1000, this.#pingMs / 4));\n const timer = setInterval(() => {\n const now = Date.now();\n if (now - lastHeard >= this.#silenceMs) {\n finish({ kind: \"lost\", code: null });\n } else if (now - lastHeard >= this.#pingMs && now - lastPing >= this.#pingMs) {\n lastPing = now;\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"ping\" });\n this.#send({ type: \"ping\" }, id);\n }\n }, tick);\n const live = (): boolean => this.#connection === handshake;\n const finish = (ending: Ending): void => {\n if (!live()) {\n return;\n }\n clearInterval(timer);\n this.#connection = null;\n this.#endServe = null;\n this.#wake = null;\n handshake.close();\n resolve(ending);\n };\n this.#connection = handshake;\n this.#endServe = finish;\n this.#wake = () => {\n if (this.#closing) {\n finish({ kind: \"stop\" });\n }\n };\n const early = handshake.handOver({\n text: (text) => {\n lastHeard = Date.now();\n lastPing = lastHeard;\n this.#onText(text);\n },\n closed: (code) => {\n finish({ kind: \"lost\", code: closeCode(code) });\n },\n });\n this.#unclaimed = new Set(resumed.filter((name) => !this.#held && !this.#topics.has(name)));\n this.#restore(resumed);\n for (const text of early) {\n if (!live()) {\n return;\n }\n this.#onText(text);\n }\n });\n }\n\n /**\n * Restores state on a new connection: resubscribes, resends unconfirmed\n * publishes, and sends queued frames.\n *\n * When the server holds the session's topics (`#held`), each topic it\n * lists as resumed that the engine tracks is subscribed again from\n * `resume`, which is one past the session's cursor. Otherwise\n * topics the server restored for the session are left to it, except\n * those whose buffer overflowed and those still waiting for the\n * `subscribed` that claims them, which are subscribed again the way the\n * application asked (`resume` for one owned by a pattern); every other\n * topic is subscribed again from the next `seq` it expects, so nothing\n * still in the log is missed.\n * A shared subscription always rejoins its group with `resume`, because\n * the group's position is on the server. Wildcard patterns are sent\n * after the topics, in name order, from `{\"seq\": 1}`: the server skips\n * topics the connection holds, so that joins only topics created during\n * the disconnect, from their first message.\n *\n * @param resumed - Topics the server restored.\n */\n #restore(resumed: string[]): void {\n const restored = new Set(resumed);\n for (const [name, topic] of this.#topics) {\n if (topic.group !== null) {\n this.#sendSubscribe(name, topic.generation, \"resume\", topic.group);\n } else if (topic.claiming) {\n this.#sendSubscribe(name, topic.generation, topic.owner === null ? topic.from : \"resume\", null);\n } else if (!restored.has(name) || topic.overflowed) {\n const next = topic.tracker.nextExpected;\n this.#sendSubscribe(name, topic.generation, next === null ? topic.from : { seq: next }, null);\n } else if (this.#held) {\n this.#sendSubscribe(name, topic.generation, \"resume\", null);\n }\n topic.overflowed = false;\n }\n for (const name of [...this.#patterns.keys()].sort()) {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined) {\n this.#sendSubscribe(name, pattern.generation, { seq: 1 }, null);\n }\n }\n for (const [id, message] of this.#unconfirmed) {\n this.#send(message, id);\n }\n this.#flushOffline();\n }\n\n /**\n * Sends a subscribe and records it as pending.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription it is for.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n */\n #sendSubscribe(topic: string, generation: number, from: WireStartFrom, group: string | null): void {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"subscribe\", topic, generation });\n this.#send(\n group === null ? { type: \"subscribe\", topic, from } : { type: \"subscribe\", topic, from, group },\n id,\n );\n }\n\n /**\n * Queues a frame to send once connected, dropping the oldest beyond `OFFLINE_LIMIT`.\n *\n * @param message - A QoS 0 publish or an unsubscribe.\n */\n #queueOffline(message: ClientMessage): void {\n if (this.#offline.length >= OFFLINE_LIMIT) {\n this.#offline.shift();\n }\n this.#offline.push(message);\n }\n\n /** Sends every queued frame, if connected. Unsubscribes get an id. */\n #flushOffline(): void {\n if (this.#connection === null) {\n return;\n }\n const queued = this.#offline;\n this.#offline = [];\n for (const message of queued) {\n this.#send(message, message.type === \"unsubscribe\" ? this.#takeId() : undefined);\n }\n }\n\n /**\n * Sends a frame if connected. A frame sent while the socket is closing is\n * lost with it; the close that follows decides what is resent.\n *\n * @param message - The frame.\n * @param id - The request id, when a reply is expected.\n */\n #send(message: ClientMessage, id?: number): void {\n const socket = this.#connection?.socket;\n if (socket?.readyState !== WebSocket.OPEN) {\n return;\n }\n socket.send(encodeFrame(message, id));\n }\n\n /**\n * Takes a request id.\n *\n * @returns A new id.\n */\n #takeId(): number {\n const id = this.#nextId;\n this.#nextId += 1;\n return id;\n }\n\n /**\n * Stops tracking one topic. A topic subscribed by name has its\n * subscription ended; a topic owned by a pattern only stops, and the\n * pattern's subscription carries on.\n *\n * @param topic - The topic.\n * @returns Whether it was tracked.\n */\n #dropTopic(topic: string): boolean {\n const entry = this.#topics.get(topic);\n if (entry === undefined) {\n return false;\n }\n this.#topics.delete(topic);\n if (entry.owner === null) {\n entry.channel.end();\n }\n return true;\n }\n\n /**\n * Starts tracking a topic the server joined for one of this client's\n * wildcard subscriptions. When several patterns match, the oldest owns it.\n *\n * @param name - The topic.\n * @param start - The first `seq` the server will send, or `null` when unknown.\n * @returns The tracked topic, or `undefined` when no pattern matches.\n */\n #adopt(name: string, start: number | null): Topic | undefined {\n let owner: string | null = null;\n let oldest: Pattern | null = null;\n for (const [pattern, entry] of this.#patterns) {\n if (matchesPattern(pattern, name) && (oldest === null || entry.generation < oldest.generation)) {\n owner = pattern;\n oldest = entry;\n }\n }\n if (owner === null || oldest === null) {\n return undefined;\n }\n const tracker = new DeliveryTracker();\n tracker.nextExpected = start;\n const topic: Topic = {\n channel: oldest.channel,\n from: { seq: start ?? 1 },\n generation: oldest.generation,\n tracker,\n overflowed: false,\n owner,\n group: null,\n claiming: false,\n };\n this.#topics.set(name, topic);\n return topic;\n }\n\n /**\n * Moves a held pattern to a new subscription. The topics it owned are\n * pointed at the new channel and generation and keep their trackers, so\n * each keeps the next `seq` it expects: the server sends nothing again\n * for topics the connection holds. The earlier channel ends; what it\n * still holds can be taken or dropped without any effect on the topics.\n * Acknowledgements held back for the earlier channel's full buffer are\n * sent now, because nothing will report those messages as taken to the\n * new subscription.\n *\n * @param pattern - The pattern, which must be held.\n * @param channel - The new subscription's channel.\n * @param generation - The new subscription.\n */\n #replacePattern(pattern: string, channel: Channel, generation: number): void {\n this.#patterns.get(pattern)?.channel.end();\n for (const [name, topic] of this.#topics) {\n if (topic.owner !== pattern) {\n continue;\n }\n topic.channel = channel;\n topic.generation = generation;\n for (const seq of topic.tracker.deferred) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n }\n topic.tracker.deferred.clear();\n }\n }\n\n /**\n * Claims every unclaimed topic of the session a pattern matches: each\n * stops being unclaimed and is tracked as owned by the pattern, with\n * `claiming` set until its own `subscribed` arrives.\n *\n * @param pattern - The pattern.\n * @param channel - The pattern's channel.\n * @param generation - The pattern's subscription.\n * @returns The claimed topics in name order, each of which needs a\n * subscribe by name with `from: \"resume\"`.\n */\n #claimMatching(pattern: string, channel: Channel, generation: number): string[] {\n const claimed = [...this.#unclaimed].filter((name) => matchesPattern(pattern, name)).sort();\n for (const name of claimed) {\n this.#unclaimed.delete(name);\n this.#topics.set(name, {\n channel,\n from: \"resume\",\n generation,\n tracker: new DeliveryTracker(),\n overflowed: false,\n owner: pattern,\n group: null,\n claiming: true,\n });\n }\n return claimed;\n }\n\n /**\n * Stops tracking a subscription and ends it: a topic subscribed by name,\n * or a wildcard pattern together with every topic joined through it.\n *\n * @param name - The topic or pattern.\n * @param generation - Only release it if it is still this subscription;\n * `null` releases whatever is there.\n * @returns What to unsubscribe from on the server: the name first, and\n * for a pattern the topics it owned. Empty when nothing was released.\n */\n #release(name: string, generation: number | null): string[] {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined && (generation === null || pattern.generation === generation)) {\n this.#patterns.delete(name);\n pattern.channel.end();\n const names = [name];\n for (const [topic, entry] of this.#topics) {\n if (entry.owner === name) {\n this.#topics.delete(topic);\n names.push(topic);\n }\n }\n return names;\n }\n const topic = this.#topics.get(name);\n if (topic?.owner === null && (generation === null || topic.generation === generation)) {\n this.#topics.delete(name);\n topic.channel.end();\n return [name];\n }\n return [];\n }\n\n /**\n * Unsubscribes without waiting, when the application closes a\n * subscription, if the topic or pattern still belongs to it. A pattern's\n * owned topics are unsubscribed with it.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription being closed.\n */\n #forget(topic: string, generation: number): void {\n const released = this.#release(topic, generation);\n if (released.length === 0) {\n return;\n }\n this.#subscribeWaiters.get(topic)?.reject(PopSubError.closed(null));\n this.#subscribeWaiters.delete(topic);\n for (const name of released) {\n if (this.#connection === null) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n } else {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n }\n this.#wake?.();\n }\n\n /**\n * Called when the application takes a message: sends an acknowledgement\n * held back for a full buffer, and lets a paused client reconnect once\n * there is room.\n *\n * @param topic - The topic.\n * @param generation - The subscription the message came from.\n * @param message - The message taken.\n */\n #taken(topic: string, generation: number, message: Message): void {\n const entry = this.#topics.get(topic);\n if (entry?.generation === generation && entry.tracker.deferred.delete(message.seq)) {\n entry.tracker.acked.insert(message.seq);\n this.#send({ type: \"ack\", topic, seq: message.seq });\n }\n this.#wake?.();\n }\n\n /**\n * Parses a frame and acts on it; frames this client doesn't know are ignored.\n *\n * @param text - The frame's text.\n */\n #onText(text: string): void {\n const frame = parseServerFrame(text);\n if (frame !== null) {\n this.#onFrame(frame);\n }\n }\n\n /**\n * Acts on a frame from the server. A reply's pending entry is removed by\n * its id first, so a `pong` needs nothing more: hearing it at all is what\n * keeps the connection from being given up as silent. A `subscribed` for\n * a topic being claimed ends the claim and starts its next expected `seq`\n * over at `replay_from`.\n *\n * @param frame - The frame.\n */\n #onFrame(frame: ServerFrame): void {\n const id = typeof frame.id === \"number\" ? frame.id : null;\n const pending = id === null ? undefined : this.#pending.get(id);\n if (id !== null) {\n this.#pending.delete(id);\n }\n if (pending?.kind === \"request\") {\n if (frame.type === \"error\") {\n pending.settle.reject(\n PopSubError.server(errorCode(frame.code), frame.message, frame.retry_after ?? null),\n );\n } else {\n pending.settle.resolve(frame);\n }\n return;\n }\n const unprompted = frame.id === undefined || frame.id === null;\n switch (frame.type) {\n case \"message\":\n this.#deliver(frame);\n break;\n case \"subscribed\": {\n if (!this.#patterns.has(frame.topic)) {\n const tracked = this.#topics.get(frame.topic);\n if (tracked === undefined) {\n this.#adopt(frame.topic, frame.replay_from);\n } else {\n if (tracked.claiming) {\n tracked.claiming = false;\n tracked.tracker.nextExpected = null;\n }\n tracked.tracker.moveTo(frame.replay_from);\n }\n }\n const waiter = this.#subscribeWaiters.get(frame.topic);\n if (waiter !== undefined) {\n this.#subscribeWaiters.delete(frame.topic);\n waiter.resolve();\n }\n break;\n }\n case \"unsubscribed\":\n if (pending?.kind === \"unsubscribe\") {\n pending.settle.resolve();\n } else if (unprompted && this.#dropTopic(frame.topic)) {\n this.emitter.emit({ type: \"unsubscribed\", topic: frame.topic });\n }\n break;\n case \"published\":\n if (pending?.kind === \"publish\" && id !== null) {\n this.#unconfirmed.delete(id);\n pending.settle.resolve({ seq: frame.seq, messageId: frame.message_id });\n }\n break;\n case \"truncated\":\n this.#topics.get(frame.topic)?.tracker.moveTo(frame.first_available);\n this.emitter.emit({ type: \"truncated\", topic: frame.topic, firstAvailable: frame.first_available });\n break;\n case \"stalled\":\n this.emitter.emit({ type: \"stalled\", topic: frame.topic, seq: frame.seq });\n break;\n case \"auth_expiring\":\n this.emitter.emit({ type: \"authExpiring\", expiresAtMs: frame.expires_at_ms });\n if (\"password\" in this.#config.credentials) {\n const loginId = this.#takeId();\n this.#pending.set(loginId, { kind: \"relogin\" });\n const { username, password } = this.#config.credentials;\n this.#send({ type: \"login\", username, password }, loginId);\n }\n break;\n case \"logged_in\":\n if (pending?.kind === \"relogin\") {\n const authId = this.#takeId();\n this.#pending.set(authId, { kind: \"reauth\" });\n this.#send({ type: \"auth\", token: frame.token, protocol: PROTOCOL_VERSION }, authId);\n }\n break;\n case \"authenticated\":\n if (pending?.kind === \"reauth\") {\n this.emitter.emit({ type: \"authRefreshed\" });\n }\n break;\n case \"pong\":\n break;\n case \"error\":\n this.#onError(pending, id, frame);\n break;\n default:\n break;\n }\n }\n\n /**\n * Routes an error frame to the request it answers, or to the events. A\n * refused subscribe ends that subscription; a refused resubscribe of a\n * topic owned by a pattern only stops tracking that topic.\n *\n * @param pending - The request it answers, if its id matched one.\n * @param id - Its request id, if it had one.\n * @param frame - The error frame.\n */\n #onError(\n pending: Pending | undefined,\n id: number | null,\n frame: Extract<ServerMessage, { type: \"error\" }>,\n ): void {\n const code = errorCode(frame.code);\n const error = PopSubError.server(code, frame.message, frame.retry_after ?? null);\n switch (pending?.kind) {\n case \"subscribe\": {\n const released = this.#release(pending.topic, pending.generation).length > 0;\n const owned = this.#topics.get(pending.topic);\n if (!released && owned?.owner != null && owned.generation === pending.generation) {\n this.#topics.delete(pending.topic);\n }\n if (released) {\n const waiter = this.#subscribeWaiters.get(pending.topic);\n this.#subscribeWaiters.delete(pending.topic);\n waiter?.reject(error);\n }\n break;\n }\n case \"unsubscribe\":\n pending.settle.reject(error);\n break;\n case \"publish\":\n if (id !== null) {\n this.#unconfirmed.delete(id);\n }\n pending.settle.reject(error);\n break;\n case \"ping\":\n break;\n default:\n this.emitter.emit({ type: \"serverError\", code, message: frame.message });\n break;\n }\n }\n\n /**\n * Hands a delivered message to its subscription, dropping duplicates,\n * acknowledging as the ack mode says, and holding back when the buffer is\n * full. A message for an untracked topic is adopted by the oldest\n * matching wildcard pattern; when none matches it is acknowledged and dropped.\n *\n * A message on a topic the server holds for the session that the\n * application hasn't subscribed to here, or whose subscribe is still\n * unanswered, is dropped without an acknowledgement: the server keeps it\n * and replays it when the application's subscribe is handled.\n *\n * @param delivery - The delivered message.\n */\n #deliver(delivery: Extract<ServerMessage, { type: \"message\" }>): void {\n const { topic: name, seq } = delivery;\n const qos: 0 | 1 = delivery.qos === 1 ? 1 : 0;\n if (this.#unclaimed.has(name)) {\n return;\n }\n const topic = this.#topics.get(name) ?? this.#adopt(name, null);\n if (topic === undefined) {\n if (qos === 1) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n if (topic.overflowed || topic.claiming) {\n return;\n }\n const automatic = this.#config.ackMode === \"auto\";\n if (topic.tracker.isDuplicate(seq)) {\n if (qos === 1 && topic.tracker.reacksDuplicate(seq, automatic)) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n const buffered = topic.channel.size;\n if (buffered >= this.#config.subscriptionBuffer + this.#maxInflight) {\n topic.overflowed = true;\n this.#endServe?.({ kind: \"pause\" });\n return;\n }\n topic.tracker.accept(seq);\n let acker: (() => void) | null = null;\n if (qos === 1) {\n if (!automatic) {\n acker = () => {\n this.ack(name, seq);\n };\n } else if (buffered < this.#config.subscriptionBuffer) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n } else {\n topic.tracker.deferred.add(seq);\n }\n }\n topic.channel.push(\n new Message(\n {\n topic: name,\n seq,\n messageId: delivery.message_id,\n payload: delivery.payload,\n encoding: delivery.encoding === \"base64\" ? \"base64\" : null,\n qos,\n publishedAtMs: delivery.published_at_ms,\n },\n acker,\n ),\n );\n }\n\n /**\n * Fails every admin request still waiting when a connection ends: the\n * server may or may not have carried it out. `ping`s, token refreshes and\n * subscribes of the old connection are forgotten; subscribes are sent\n * again by `#restore`.\n */\n #failRequests(): void {\n for (const [id, pending] of this.#pending) {\n if (pending.kind === \"request\") {\n this.#pending.delete(id);\n pending.settle.reject(\n new PopSubError(\n \"connect\",\n \"the connection dropped before the reply; the request may or may not have been carried out\",\n ),\n );\n } else if (\n pending.kind === \"ping\" ||\n pending.kind === \"relogin\" ||\n pending.kind === \"reauth\" ||\n pending.kind === \"subscribe\"\n ) {\n this.#pending.delete(id);\n }\n }\n }\n\n /**\n * Throws if the client has stopped.\n *\n * @throws PopSubError of kind `closed` with the close code that stopped it.\n */\n #throwIfStopped(): void {\n if (this.#stopped !== null) {\n throw PopSubError.closed(this.#stopped.code);\n }\n }\n\n /**\n * Stops the client for good: records why, fails everything waiting, ends\n * every subscription, and removes every event listener.\n *\n * @param code - The close code that stopped it, if any.\n * @param cause - The unexpected exception that stopped it, if any.\n */\n #stop(code: CloseCode | null, cause?: unknown): void {\n this.#endServe?.({ kind: \"stop\" });\n this.#wake = null;\n this.#stopped = { code };\n const error = PopSubError.closed(code);\n this.#ready?.reject(\n cause === undefined\n ? error\n : new PopSubError(\n \"closed\",\n `the client stopped unexpectedly: ${cause instanceof Error ? cause.message : \"unknown error\"}`,\n { cause },\n ),\n );\n this.#ready = null;\n for (const waiter of this.#subscribeWaiters.values()) {\n waiter.reject(error);\n }\n this.#subscribeWaiters.clear();\n for (const pending of this.#pending.values()) {\n if (pending.kind === \"unsubscribe\" || pending.kind === \"publish\" || pending.kind === \"request\") {\n pending.settle.reject(error);\n }\n }\n this.#pending.clear();\n this.#unconfirmed.clear();\n this.#offline = [];\n for (const topic of this.#topics.values()) {\n topic.channel.end();\n }\n this.#topics.clear();\n for (const pattern of this.#patterns.values()) {\n pattern.channel.end();\n }\n this.#patterns.clear();\n this.#unclaimed.clear();\n this.emitter.clear();\n this.#finish();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"engine.js","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8FG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AACzD,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EACL,SAAS,EACT,WAAW,EACX,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,eAAe,GAQhB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEnE,kGAAkG;AAClG,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC;AAEpC,gGAAgG;AAChG,MAAM,kBAAkB,GAAG,OAAO,CAAC;AAEnC,uGAAuG;AACvG,MAAM,eAAe,GAAG,MAAM,CA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AAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;YAC1C,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACtB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,EAAE,CAAC;YAC9C,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;QACxB,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC;QACvB,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF;AAED;;;;;;;GAOG;AACH,KAAK,UAAU,UAAU,CAAC,QAA+B;IACvD,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACH,KAAK,GAAG,MAAM,QAAQ,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvE,MAAM,IAAI,WAAW,CAAC,SAAS,EAAE,8BAA8B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IAC9F,CAAC;IACD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,EAAE,EAAE,CAAC;QAC9C,MAAM,IAAI,WAAW,CAAC,SAAS,EAAE,sCAAsC,CAAC,CAAC;IAC3E,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * The engine behind a `Client`: it owns the WebSocket and does what every\n * application would otherwise have to.\n *\n * It connects, logs in and authenticates, then serves the connection until\n * it ends. The close code decides what happens next: reconnect with\n * jittered backoff, or stop for good (`session_taken_over`,\n * `unsupported_protocol`, `auth_failed`, `account_disabled`, rejected\n * credentials, and `token_expired` with a fixed token). After\n * reconnecting it resubscribes every topic from the next `seq` it expects\n * (a topic the server lists as resumed for a durable session is instead\n * subscribed again from `resume` when the server holds the session's\n * topics, and otherwise left to the server unless a claim on it is still\n * unanswered; see below), resends confirmed publishes that never got their `published` under the\n * same request id and `message_id`, and sends QoS 0 publishes and\n * unsubscribes queued while disconnected.\n *\n * Every message is checked against the next `seq` its topic expects, so a\n * retry or a replay never reaches the application twice. A duplicate the\n * application acknowledged before (or any duplicate in automatic mode,\n * unless its acknowledgement is held back for a full buffer) is\n * acknowledged again, so a lost acknowledgement can't stall the topic.\n *\n * A durable session outlives the process. When a new process connects\n * with the same session id, the server lists the session's topics in\n * `authenticated.resumed` before the application has subscribed to\n * anything. The engine must never acknowledge a message the application\n * couldn't have received, so with a session id its `auth` carries\n * `hold_resumed: true`. A server that honours it answers `held: true` and\n * sends nothing on a resumed topic until the engine subscribes to it. Then\n * nothing is unclaimed, a subscribe to a resumed topic is an ordinary\n * subscribe, a pattern needs no subscribes by name, and after a reconnect\n * the engine subscribes again to every tracked topic the server lists as\n * resumed, with `from: \"resume\"`, because the server no longer does it.\n *\n * A server that doesn't know `hold_resumed` answers without `held` and\n * sends what it kept for the resumed topics at once. A resumed topic the engine\n * isn't tracking is unclaimed: its messages are dropped without an\n * acknowledgement, so the server keeps them for the session. Subscribing\n * to an unclaimed topic by name, or to a pattern that matches it, claims\n * it. A claimed topic is tracked, but its messages are still dropped\n * unacknowledged until the `subscribed` that answers the claim arrives,\n * because the subscribe replays them in order from `replay_from`. A\n * pattern claims a topic by sending one more `subscribe` for it by name\n * with `from: \"resume\"`, since the server skips topics the connection\n * holds when it handles the pattern itself. After a reconnect a claim\n * still unanswered is sent again even when the server lists the topic as\n * resumed. A topic the application never subscribes to stays unclaimed.\n *\n * A wildcard subscription (`orders/#`) is one pattern with one channel.\n * The server announces each topic it joins for the pattern with a\n * `subscribed` frame that has no id; the engine then tracks that topic\n * like any other, with its own next expected `seq` and acknowledgement\n * memory, owned by the pattern and feeding the pattern's channel. A\n * `subscribed` or `message` for an untracked topic is matched against the\n * patterns, and the oldest matching one owns it. After a reconnect the\n * tracked topics are resubscribed first, then each pattern is sent again\n * with `from: {\"seq\": 1}`, which joins only topics created meanwhile.\n * Subscribing again to a pattern the engine holds replaces the\n * subscription: the topics it owned move to the new channel and keep\n * their next expected `seq`, because the server sends nothing again for\n * topics the connection holds, and the earlier channel ends.\n *\n * A shared subscription (a topic read through a `group`) gets only some of\n * the topic's messages, out of order, so duplicates are found with a\n * bounded set of delivered `seq`s instead of a next expected one, nothing\n * moves on `subscribed.replay_from` or `truncated`, and after a reconnect\n * it always rejoins the group with `from: \"resume\"`.\n *\n * An `unsubscribed` frame with no id means the server ended the\n * subscription; every unsubscribe the engine sends carries an id so its\n * reply is never mistaken for that.\n *\n * The browser `WebSocket` API can't pause reading, so backpressure works in\n * two steps. While a subscription's buffer holds `subscriptionBuffer`\n * messages or more, automatic acknowledgements of new QoS 1 messages wait\n * until the application takes them; the server's per-subscription window\n * (`limits.max_inflight`) then stops sending to it, QoS 0 included. If the\n * buffer still reaches `subscriptionBuffer + max_inflight` (possible with\n * QoS 0 traffic, which no window paces), the engine drops the connection,\n * waits until the application has taken that buffer down to half of\n * `subscriptionBuffer`, reconnects, and resubscribes that topic from the\n * next `seq` it expects, so the log fills the gap. Memory per subscription\n * stays below `subscriptionBuffer + max_inflight` messages.\n *\n * Nor does the API show the server's WebSocket pings, so silence is\n * detected with the protocol's own `ping` request: after `heartbeat_secs`\n * with nothing from the server the engine sends `ping` with an id, and\n * again after each further `heartbeat_secs` of silence. Any frame,\n * including the `pong` reply, counts as hearing from the server. Once\n * `idle_timeout_secs + heartbeat_secs` pass with nothing at all, the\n * connection is given up and the engine reconnects.\n *\n * @module\n */\n\nimport { jitteredDelay } from \"./backoff.js\";\nimport type { ResolvedConfig } from \"./config.js\";\nimport { ACK_MEMORY, DeliveryTracker } from \"./dedup.js\";\nimport { Emitter } from \"./events.js\";\nimport { PopSubError } from \"./errors.js\";\nimport { Aborted, ConnectFailure, Handshake } from \"./handshake.js\";\nimport { isPattern, matchesPattern } from \"./pattern.js\";\nimport {\n closeCode,\n encodeFrame,\n errorCode,\n parseServerFrame,\n PROTOCOL_VERSION,\n publishFrame,\n shouldReconnect,\n type ClientMessage,\n type CloseCode,\n type Encoding,\n type Limits,\n type ServerFrame,\n type ServerMessage,\n type WireStartFrom,\n} from \"./protocol.js\";\nimport { Channel, Message, Subscription } from \"./subscription.js\";\n\n/** How many QoS 0 publishes and unsubscribes are held while disconnected; the oldest go first. */\nexport const OFFLINE_LIMIT = 10_000;\n\n/** How long to wait for anything from the server before the server has announced its limits. */\nconst DEFAULT_SILENCE_MS = 120_000;\n\n/** How long a connection may be silent before a `ping`, before the server has announced its limits. */\nconst DEFAULT_PING_MS = 30_000;\n\n/** The window size assumed before the server has announced its limits. */\nconst DEFAULT_MAX_INFLIGHT = 100;\n\n/** The result of a confirmed publish. */\nexport interface Published {\n /** The message's position in the topic. */\n seq: number;\n /** The id it was stored under. */\n messageId: string;\n}\n\n/** How to settle a caller's promise. */\ninterface Settle<T> {\n /** Fulfils it. */\n resolve(value: T): void;\n /** Rejects it. */\n reject(error: PopSubError): void;\n}\n\n/** A request waiting for its reply, by request id. */\ntype Pending =\n | { kind: \"subscribe\"; topic: string; generation: number }\n | { kind: \"unsubscribe\"; settle: Settle<void> }\n | { kind: \"publish\"; settle: Settle<Published> }\n | { kind: \"request\"; settle: Settle<ServerMessage> }\n | { kind: \"relogin\" }\n | { kind: \"reauth\" }\n | { kind: \"ping\" };\n\n/** One subscribed topic. */\ninterface Topic {\n /** Where its messages go. */\n channel: Channel;\n /** Where replay started when the application subscribed. */\n from: WireStartFrom;\n /** Which subscription this is, so a stale close can't remove a newer one. */\n generation: number;\n /** The next expected `seq` and acknowledgement memory. */\n tracker: DeliveryTracker;\n /** Whether its buffer overflowed, so deliveries are dropped until it is resubscribed. */\n overflowed: boolean;\n /** The wildcard pattern it was joined through, or `null` when subscribed by name. */\n owner: string | null;\n /** The shared subscription's group, or `null` for an ordinary subscription. */\n group: string | null;\n /**\n * Whether the server held this topic for the session before the\n * application subscribed, and the `subscribed` that answers the\n * application's subscribe hasn't arrived yet. Until it does, messages on\n * the topic are the server's own resume: they are dropped without an\n * acknowledgement, because the subscribe replays them.\n */\n claiming: boolean;\n}\n\n/** One wildcard subscription. */\ninterface Pattern {\n /** Where the messages of every topic it owns go. */\n channel: Channel;\n /** Which subscription this is; the oldest matching pattern owns a new topic. */\n generation: number;\n}\n\n/** How a served connection ended. */\ntype Ending = { kind: \"stop\" } | { kind: \"lost\"; code: CloseCode | null } | { kind: \"pause\" };\n\n/** The outcome of one connection attempt. */\ntype Attempt =\n | { kind: \"connected\"; handshake: Handshake; resumed: string[] }\n | { kind: \"failed\"; failure: ConnectFailure }\n | { kind: \"stopped\" };\n\n/**\n * Creates a version 4 UUID, with `crypto.randomUUID` where the runtime has\n * it (browsers only offer it on secure origins) and `getRandomValues`\n * otherwise.\n *\n * @returns The UUID.\n */\nexport function uuid(): string {\n const crypto = globalThis.crypto;\n if (typeof crypto.randomUUID === \"function\") {\n return crypto.randomUUID();\n }\n const bytes = crypto.getRandomValues(new Uint8Array(16));\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/**\n * Turns an unexpected reply during connecting into a failure.\n *\n * @param reply - What the server sent instead of the expected reply.\n * @returns The failure; retryable only for the server's temporary refusals\n * and for replies of the wrong type.\n */\nfunction refusal(reply: ServerMessage): ConnectFailure {\n if (reply.type === \"error\") {\n const error = PopSubError.server(errorCode(reply.code), reply.message, reply.retry_after ?? null);\n return new ConnectFailure(error, error.isTemporary());\n }\n return new ConnectFailure(new PopSubError(\"protocol\", `unexpected ${reply.type} while connecting`), true);\n}\n\n/** The state and the run loop behind one `Client`. */\nexport class Engine {\n /** How to connect. */\n readonly #config: ResolvedConfig;\n /** Where events go. */\n readonly emitter = new Emitter();\n /** Subscribed topics. */\n readonly #topics = new Map<string, Topic>();\n /** Wildcard subscriptions, by pattern. */\n readonly #patterns = new Map<string, Pattern>();\n /**\n * Topics the server restored for the session that the application hasn't\n * subscribed to in this process. Their messages are dropped without an\n * acknowledgement, so the server keeps them for the session.\n */\n #unclaimed = new Set<string>();\n /**\n * Whether the server left the session's topics unattached on this\n * connection (`authenticated.held`). Then nothing arrives on a topic\n * until the engine subscribes to it, so nothing is unclaimed, and\n * `#restore` subscribes to the resumed topics itself.\n */\n #held = false;\n /** Subscribes waiting for `subscribed`, by topic. */\n readonly #subscribeWaiters = new Map<string, Settle<void>>();\n /** Requests waiting for a reply, by id. */\n readonly #pending = new Map<number, Pending>();\n /** Confirmed publishes not yet confirmed, by request id, in id order, for resending. */\n readonly #unconfirmed = new Map<number, ClientMessage>();\n /** QoS 0 publishes and unsubscribes to send once connected. */\n #offline: ClientMessage[] = [];\n /** The next request id. */\n #nextId = 1;\n /** The next subscription generation. */\n #nextGeneration = 1;\n /** Whether a connection has ever succeeded, so `clean_start` is only sent once. */\n #connectedOnce = false;\n /** How long to wait for anything from the server before giving up on the connection. */\n #silenceMs = DEFAULT_SILENCE_MS;\n /** How long a connection may be silent before a `ping`, and between `ping`s while it stays silent. */\n #pingMs = DEFAULT_PING_MS;\n /** The server's per-subscription window. */\n #maxInflight = DEFAULT_MAX_INFLIGHT;\n /** The served connection, while there is one. */\n #connection: Handshake | null = null;\n /** Ends the served connection, while there is one. */\n #endServe: ((ending: Ending) => void) | null = null;\n /** Re-checks whatever the run loop is waiting for; set by each wait. */\n #wake: (() => void) | null = null;\n /** Whether the application asked to close. */\n #closing = false;\n /** Why the client stopped, once it has. */\n #stopped: { code: CloseCode | null } | null = null;\n /** Settles when the first connection is up, or rejects with what stopped the client first. */\n readonly ready: Promise<void>;\n /** Settles `ready`. */\n #ready: Settle<void> | null = null;\n /** Settles when the run loop has finished and the client has stopped. */\n readonly finished: Promise<void>;\n /** Settles `finished`. */\n #finish: () => void = () => undefined;\n\n /**\n * Builds an engine and starts its run loop.\n *\n * @param config - How to connect.\n */\n constructor(config: ResolvedConfig) {\n this.#config = config;\n this.ready = new Promise<void>((resolve, reject) => {\n this.#ready = { resolve, reject };\n });\n this.ready.catch(() => undefined);\n this.finished = new Promise<void>((resolve) => {\n this.#finish = resolve;\n });\n void this.#run();\n }\n\n /**\n * Why the client stopped, if it has.\n *\n * @returns `{ code }` once stopped (the code is `null` when the\n * application closed it or it ran out of attempts), `null` while running.\n */\n get stopped(): { code: CloseCode | null } | null {\n return this.#stopped;\n }\n\n /**\n * Subscribes to a topic or a wildcard pattern, replacing any earlier\n * subscription to the same name. With a group it joins a shared\n * subscription to the topic.\n *\n * Subscribing again to a topic by name starts over from `from`.\n * Subscribing again to a pattern keeps the topics it owned (see\n * `#replacePattern`).\n *\n * A topic the server held for the session, subscribed by name or matched\n * by the pattern, is claimed: it is tracked with `claiming` set, so what\n * the server sent on its own is dropped until the `subscribed` that\n * answers the claim. A topic subscribed again while its claim is\n * unanswered stays `claiming`. For a pattern each claimed topic gets its own\n * subscribe by name with `from: \"resume\"`, sent after the pattern's.\n * While disconnected nothing is sent; `#restore` sends the claims on the\n * next connection.\n *\n * @param topic - The topic, or a pattern such as `orders/#`.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n * @returns The subscription, and a promise that settles when the server\n * confirms it.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n subscribe(\n topic: string,\n from: WireStartFrom,\n group: string | null = null,\n ): { subscription: Subscription; done: Promise<void> } {\n this.#throwIfStopped();\n const generation = this.#nextGeneration++;\n const channel = new Channel(topic, {\n taken: (message) => {\n this.#taken(message.topic, generation, message);\n },\n leave: () => {\n this.#forget(topic, generation);\n },\n });\n const wildcard = group === null && isPattern(topic);\n const stillClaiming = this.#topics.get(topic)?.claiming === true;\n if (wildcard && this.#patterns.has(topic)) {\n this.#replacePattern(topic, channel, generation);\n } else {\n this.#release(topic, null);\n }\n this.#subscribeWaiters\n .get(topic)\n ?.reject(new PopSubError(\"protocol\", `replaced by a later subscribe to '${topic}'`));\n let claimed: string[] = [];\n if (wildcard) {\n this.#patterns.set(topic, { channel, generation });\n claimed = this.#claimMatching(topic, channel, generation);\n } else {\n this.#topics.set(topic, {\n channel,\n from,\n generation,\n tracker: new DeliveryTracker(ACK_MEMORY, group !== null),\n overflowed: false,\n owner: null,\n group,\n claiming: this.#unclaimed.delete(topic) || stillClaiming,\n });\n }\n const done = new Promise<void>((resolve, reject) => {\n this.#subscribeWaiters.set(topic, { resolve, reject });\n });\n if (this.#connection !== null) {\n this.#sendSubscribe(topic, generation, from, group);\n for (const name of claimed) {\n this.#sendSubscribe(name, generation, \"resume\", null);\n }\n }\n return { subscription: new Subscription(channel), done };\n }\n\n /**\n * Unsubscribes from a topic, or from a pattern and every topic joined\n * through it. While disconnected the unsubscribes are queued and the\n * call succeeds at once.\n *\n * @param topic - The topic or pattern.\n * @returns A promise that settles with the server's reply to the\n * unsubscribe for `topic` itself.\n */\n unsubscribe(topic: string): Promise<void> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n const released = this.#release(topic, null);\n const [first, ...owned] = released.length === 0 ? [topic] : released;\n if (this.#connection === null) {\n for (const name of [first ?? topic, ...owned]) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n }\n return Promise.resolve();\n }\n return new Promise<void>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"unsubscribe\", settle: { resolve, reject } });\n this.#send({ type: \"unsubscribe\", topic: first ?? topic }, id);\n for (const name of owned) {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n });\n }\n\n /**\n * Publishes at QoS 0. While disconnected the publish is queued.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @throws PopSubError of kind `closed` when the client has stopped.\n */\n publish(topic: string, payload: string, encoding: Encoding | null = null): void {\n this.#throwIfStopped();\n this.#queueOffline(publishFrame(topic, payload, encoding));\n this.#flushOffline();\n }\n\n /**\n * Publishes at QoS 1 under a new `message_id`, resending it after every\n * reconnect until the server confirms it.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @returns A promise that settles with the `seq` and id once stored.\n */\n publishConfirmed(topic: string, payload: string, encoding: Encoding | null = null): Promise<Published> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n return new Promise<Published>((resolve, reject) => {\n const id = this.#takeId();\n const message: ClientMessage = {\n ...publishFrame(topic, payload, encoding),\n message_id: uuid(),\n qos: 1,\n };\n this.#pending.set(id, { kind: \"publish\", settle: { resolve, reject } });\n this.#unconfirmed.set(id, message);\n if (this.#connection !== null) {\n this.#send(message, id);\n }\n });\n }\n\n /**\n * Acknowledges a message (from `Message.ack`). While disconnected it is\n * only remembered, so a redelivery is acknowledged again.\n *\n * @param topic - The topic.\n * @param seq - The message's `seq`.\n */\n ack(topic: string, seq: number): void {\n this.#topics.get(topic)?.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic, seq });\n }\n\n /**\n * Sends a request that is never queued while disconnected and never\n * resent (the admin requests), and returns its reply.\n *\n * @param message - The request.\n * @returns A promise that settles with the reply, rejecting with a\n * `server` error for an `error` frame, or `connect` when disconnected\n * or when the connection drops first.\n */\n request(message: ClientMessage): Promise<ServerMessage> {\n if (this.#stopped !== null) {\n return Promise.reject(PopSubError.closed(this.#stopped.code));\n }\n if (this.#connection === null) {\n return Promise.reject(\n new PopSubError(\"connect\", \"not connected; this request isn't queued while disconnected\"),\n );\n }\n return new Promise<ServerMessage>((resolve, reject) => {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"request\", settle: { resolve, reject } });\n this.#send(message, id);\n });\n }\n\n /**\n * Closes the connection and stops the client. Pending requests fail with\n * a `closed` error.\n *\n * @returns A promise that settles once the client has stopped.\n */\n close(): Promise<void> {\n if (this.#stopped === null) {\n this.#closing = true;\n this.#wake?.();\n }\n return this.finished;\n }\n\n /**\n * Runs until the client stops, then stops it. An unexpected exception\n * stops the client too, and becomes the cause of the error `ready`\n * rejects with, so the returned promise never rejects.\n */\n async #run(): Promise<void> {\n try {\n this.#stop(await this.#loop());\n } catch (error) {\n this.#stop(null, error);\n }\n }\n\n /**\n * Connects, serves the connection, reconnects with backoff, and settles\n * `ready` with the first outcome, until the client must stop.\n *\n * @returns The close code that stopped the client, or `null` when the\n * application closed it, it ran out of attempts, or connecting failed\n * in a way retrying can't fix.\n */\n async #loop(): Promise<CloseCode | null> {\n let attempt = 0;\n let lastError: PopSubError | null = null;\n while (!this.#closing) {\n const outcome = await this.#connectOnce();\n if (outcome.kind === \"stopped\") {\n break;\n }\n if (outcome.kind === \"connected\") {\n attempt = 0;\n this.#connectedOnce = true;\n this.#ready?.resolve();\n this.#ready = null;\n this.emitter.emit({ type: \"connected\", resumed: outcome.resumed });\n const ending = await this.#serve(outcome.handshake, outcome.resumed);\n if (ending.kind === \"stop\") {\n break;\n }\n this.#failRequests();\n if (ending.kind === \"pause\") {\n this.emitter.emit({ type: \"disconnected\", code: null, reconnecting: true });\n if (!(await this.#waitForRoom())) {\n break;\n }\n continue;\n }\n const reconnecting = this.#shouldReconnect(ending.code);\n this.emitter.emit({ type: \"disconnected\", code: ending.code, reconnecting });\n if (!reconnecting) {\n return ending.code;\n }\n } else {\n lastError = outcome.failure.error;\n if (!outcome.failure.retry) {\n this.#ready?.reject(outcome.failure.error);\n this.#ready = null;\n break;\n }\n }\n attempt += 1;\n const maxAttempts = this.#config.reconnect.maxAttempts;\n if (maxAttempts !== null && attempt > maxAttempts) {\n const reason = lastError === null ? \"\" : `; the last attempt failed: ${lastError.message}`;\n this.#ready?.reject(\n new PopSubError(\"connect\", `ran out of reconnect attempts${reason}`, { cause: lastError }),\n );\n this.#ready = null;\n break;\n }\n if (!(await this.#sleep(jitteredDelay(this.#config.reconnect, attempt)))) {\n break;\n }\n }\n return null;\n }\n\n /**\n * Decides whether to reconnect after a connection was lost.\n *\n * @param code - The server's close code, if it sent one.\n * @returns True to reconnect. An expired token only allows it with\n * password credentials, which log in again, or a token provider, which\n * fetches a fresh token.\n */\n #shouldReconnect(code: CloseCode | null): boolean {\n if (code === null) {\n return true;\n }\n if (code === 4004) {\n const credentials = this.#config.credentials;\n return \"password\" in credentials || \"tokenProvider\" in credentials;\n }\n return shouldReconnect(code);\n }\n\n /**\n * Waits before the next attempt, unless the application closes the client.\n *\n * @param ms - How long to wait.\n * @returns False when the application closed the client while waiting.\n */\n #sleep(ms: number): Promise<boolean> {\n return new Promise((resolve) => {\n if (this.#closing) {\n resolve(false);\n return;\n }\n const timer = setTimeout(() => {\n this.#wake = null;\n resolve(true);\n }, ms);\n this.#wake = () => {\n if (this.#closing) {\n clearTimeout(timer);\n this.#wake = null;\n resolve(false);\n }\n };\n });\n }\n\n /**\n * After a buffer overflowed, waits until every overflowed topic's buffer\n * is down to half of `subscriptionBuffer` (or the topic is gone).\n *\n * @returns False when the application closed the client while waiting.\n */\n #waitForRoom(): Promise<boolean> {\n const low = Math.floor(this.#config.subscriptionBuffer / 2);\n const drained = (): boolean =>\n [...this.#topics.values()].every((topic) => !topic.overflowed || topic.channel.size <= low);\n return new Promise((resolve) => {\n const check = (): void => {\n if (this.#closing) {\n this.#wake = null;\n resolve(false);\n } else if (drained()) {\n this.#wake = null;\n resolve(true);\n }\n };\n this.#wake = check;\n check();\n });\n }\n\n /**\n * Opens a connection, logs in if needed, and authenticates. With a\n * session id the `auth` asks the server to hold the session's topics\n * (`hold_resumed`), and `#held` records whether it did.\n *\n * @returns The authenticated connection with the topics the server\n * restored, a failure saying whether retrying could help, or `stopped`\n * when the application closed the client meanwhile.\n */\n async #connectOnce(): Promise<Attempt> {\n let handshake: Handshake;\n try {\n handshake = new Handshake(this.#config.url, this.#config.requestTimeoutMs);\n } catch (error) {\n const failure =\n error instanceof PopSubError ? error : new PopSubError(\"config\", String(error), { cause: error });\n return { kind: \"failed\", failure: new ConnectFailure(failure, false) };\n }\n this.#wake = () => {\n if (this.#closing) {\n handshake.abort();\n }\n };\n try {\n await handshake.opened();\n const credentials = this.#config.credentials;\n let token: string;\n if (\"token\" in credentials) {\n token = credentials.token;\n } else if (\"tokenProvider\" in credentials) {\n token = await fetchToken(credentials.tokenProvider);\n } else {\n const reply = await handshake.exchange(this.#takeId(), {\n type: \"login\",\n username: credentials.username,\n password: credentials.password,\n });\n if (reply.type !== \"logged_in\") {\n throw refusal(reply);\n }\n token = reply.token;\n }\n const auth: ClientMessage = { type: \"auth\", token, protocol: PROTOCOL_VERSION };\n if (this.#config.sessionId !== null) {\n auth.session_id = this.#config.sessionId;\n auth.hold_resumed = true;\n }\n if (this.#config.cleanStart && !this.#connectedOnce) {\n auth.clean_start = true;\n }\n const reply = await handshake.exchange(this.#takeId(), auth);\n if (reply.type !== \"authenticated\") {\n throw refusal(reply);\n }\n this.#applyLimits(reply.limits);\n this.#held = reply.held === true;\n return { kind: \"connected\", handshake, resumed: reply.resumed ?? [] };\n } catch (reason) {\n handshake.close();\n if (reason instanceof Aborted) {\n return { kind: \"stopped\" };\n }\n if (reason instanceof ConnectFailure) {\n return { kind: \"failed\", failure: reason };\n }\n const message = reason instanceof Error ? reason.message : String(reason);\n return {\n kind: \"failed\",\n failure: new ConnectFailure(new PopSubError(\"connect\", message, { cause: reason }), true),\n };\n } finally {\n this.#wake = null;\n }\n }\n\n /**\n * Reads the server's limits: when to `ping`, how much silence to allow,\n * and the window size.\n *\n * @param limits - The limits from `authenticated`.\n */\n #applyLimits(limits: Limits): void {\n const idle = Math.max(1, limits.idle_timeout_secs);\n const heartbeat = Math.max(1, limits.heartbeat_secs);\n this.#pingMs = heartbeat * 1000;\n this.#silenceMs = (idle + heartbeat) * 1000;\n if (Number.isFinite(limits.max_inflight) && limits.max_inflight > 0) {\n this.#maxInflight = limits.max_inflight;\n }\n }\n\n /**\n * Serves one connection until it ends. Works out which restored topics\n * are unclaimed (those the engine isn't tracking, or none when the server\n * holds the session's topics), restores subscriptions\n * and resends, then handles frames as they arrive. A timer sends `ping` while\n * the connection is silent and ends it as lost once the silence passes\n * `idle_timeout_secs + heartbeat_secs`.\n *\n * @param handshake - The authenticated connection.\n * @param resumed - Topics the server restored for the session.\n * @returns How the connection ended.\n */\n #serve(handshake: Handshake, resumed: string[]): Promise<Ending> {\n return new Promise<Ending>((resolve) => {\n let lastHeard = Date.now();\n let lastPing = lastHeard;\n const tick = Math.max(50, Math.min(1000, this.#pingMs / 4));\n const timer = setInterval(() => {\n const now = Date.now();\n if (now - lastHeard >= this.#silenceMs) {\n finish({ kind: \"lost\", code: null });\n } else if (now - lastHeard >= this.#pingMs && now - lastPing >= this.#pingMs) {\n lastPing = now;\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"ping\" });\n this.#send({ type: \"ping\" }, id);\n }\n }, tick);\n const live = (): boolean => this.#connection === handshake;\n const finish = (ending: Ending): void => {\n if (!live()) {\n return;\n }\n clearInterval(timer);\n this.#connection = null;\n this.#endServe = null;\n this.#wake = null;\n handshake.close();\n resolve(ending);\n };\n this.#connection = handshake;\n this.#endServe = finish;\n this.#wake = () => {\n if (this.#closing) {\n finish({ kind: \"stop\" });\n }\n };\n const early = handshake.handOver({\n text: (text) => {\n lastHeard = Date.now();\n lastPing = lastHeard;\n this.#onText(text);\n },\n closed: (code) => {\n finish({ kind: \"lost\", code: closeCode(code) });\n },\n });\n this.#unclaimed = new Set(resumed.filter((name) => !this.#held && !this.#topics.has(name)));\n this.#restore(resumed);\n for (const text of early) {\n if (!live()) {\n return;\n }\n this.#onText(text);\n }\n });\n }\n\n /**\n * Restores state on a new connection: resubscribes, resends unconfirmed\n * publishes, and sends queued frames.\n *\n * When the server holds the session's topics (`#held`), each topic it\n * lists as resumed that the engine tracks is subscribed again from\n * `resume`, which is one past the session's cursor. Otherwise\n * topics the server restored for the session are left to it, except\n * those whose buffer overflowed and those still waiting for the\n * `subscribed` that claims them, which are subscribed again the way the\n * application asked (`resume` for one owned by a pattern); every other\n * topic is subscribed again from the next `seq` it expects, so nothing\n * still in the log is missed.\n * A shared subscription always rejoins its group with `resume`, because\n * the group's position is on the server. Wildcard patterns are sent\n * after the topics, in name order, from `{\"seq\": 1}`: the server skips\n * topics the connection holds, so that joins only topics created during\n * the disconnect, from their first message.\n *\n * @param resumed - Topics the server restored.\n */\n #restore(resumed: string[]): void {\n const restored = new Set(resumed);\n for (const [name, topic] of this.#topics) {\n if (topic.group !== null) {\n this.#sendSubscribe(name, topic.generation, \"resume\", topic.group);\n } else if (topic.claiming) {\n this.#sendSubscribe(name, topic.generation, topic.owner === null ? topic.from : \"resume\", null);\n } else if (!restored.has(name) || topic.overflowed) {\n const next = topic.tracker.nextExpected;\n this.#sendSubscribe(name, topic.generation, next === null ? topic.from : { seq: next }, null);\n } else if (this.#held) {\n this.#sendSubscribe(name, topic.generation, \"resume\", null);\n }\n topic.overflowed = false;\n }\n for (const name of [...this.#patterns.keys()].sort()) {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined) {\n this.#sendSubscribe(name, pattern.generation, { seq: 1 }, null);\n }\n }\n for (const [id, message] of this.#unconfirmed) {\n this.#send(message, id);\n }\n this.#flushOffline();\n }\n\n /**\n * Sends a subscribe and records it as pending.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription it is for.\n * @param from - Where replay starts.\n * @param group - The shared subscription to join, or `null`.\n */\n #sendSubscribe(topic: string, generation: number, from: WireStartFrom, group: string | null): void {\n const id = this.#takeId();\n this.#pending.set(id, { kind: \"subscribe\", topic, generation });\n this.#send(\n group === null ? { type: \"subscribe\", topic, from } : { type: \"subscribe\", topic, from, group },\n id,\n );\n }\n\n /**\n * Queues a frame to send once connected, dropping the oldest beyond `OFFLINE_LIMIT`.\n *\n * @param message - A QoS 0 publish or an unsubscribe.\n */\n #queueOffline(message: ClientMessage): void {\n if (this.#offline.length >= OFFLINE_LIMIT) {\n this.#offline.shift();\n }\n this.#offline.push(message);\n }\n\n /** Sends every queued frame, if connected. Unsubscribes get an id. */\n #flushOffline(): void {\n if (this.#connection === null) {\n return;\n }\n const queued = this.#offline;\n this.#offline = [];\n for (const message of queued) {\n this.#send(message, message.type === \"unsubscribe\" ? this.#takeId() : undefined);\n }\n }\n\n /**\n * Sends a frame if connected. A frame sent while the socket is closing is\n * lost with it; the close that follows decides what is resent.\n *\n * @param message - The frame.\n * @param id - The request id, when a reply is expected.\n */\n #send(message: ClientMessage, id?: number): void {\n const socket = this.#connection?.socket;\n if (socket?.readyState !== WebSocket.OPEN) {\n return;\n }\n socket.send(encodeFrame(message, id));\n }\n\n /**\n * Fetches a fresh token from the provider and sends it as a repeat `auth`\n * on the connection that asked, which refreshes its token. If that\n * connection has ended by the time the token arrives, it is dropped: a new\n * connection fetched its own. A failed fetch is left for the connection\n * to close when its token expires, and reconnecting fetches again.\n *\n * @param provider - The token provider.\n */\n #renew(provider: () => Promise<string>): void {\n const connection = this.#connection;\n fetchToken(provider).then(\n (token) => {\n if (this.#connection !== connection) {\n return;\n }\n const authId = this.#takeId();\n this.#pending.set(authId, { kind: \"reauth\" });\n this.#send({ type: \"auth\", token, protocol: PROTOCOL_VERSION }, authId);\n },\n () => undefined,\n );\n }\n\n /**\n * Takes a request id.\n *\n * @returns A new id.\n */\n #takeId(): number {\n const id = this.#nextId;\n this.#nextId += 1;\n return id;\n }\n\n /**\n * Stops tracking one topic. A topic subscribed by name has its\n * subscription ended; a topic owned by a pattern only stops, and the\n * pattern's subscription carries on.\n *\n * @param topic - The topic.\n * @returns Whether it was tracked.\n */\n #dropTopic(topic: string): boolean {\n const entry = this.#topics.get(topic);\n if (entry === undefined) {\n return false;\n }\n this.#topics.delete(topic);\n if (entry.owner === null) {\n entry.channel.end();\n }\n return true;\n }\n\n /**\n * Starts tracking a topic the server joined for one of this client's\n * wildcard subscriptions. When several patterns match, the oldest owns it.\n *\n * @param name - The topic.\n * @param start - The first `seq` the server will send, or `null` when unknown.\n * @returns The tracked topic, or `undefined` when no pattern matches.\n */\n #adopt(name: string, start: number | null): Topic | undefined {\n let owner: string | null = null;\n let oldest: Pattern | null = null;\n for (const [pattern, entry] of this.#patterns) {\n if (matchesPattern(pattern, name) && (oldest === null || entry.generation < oldest.generation)) {\n owner = pattern;\n oldest = entry;\n }\n }\n if (owner === null || oldest === null) {\n return undefined;\n }\n const tracker = new DeliveryTracker();\n tracker.nextExpected = start;\n const topic: Topic = {\n channel: oldest.channel,\n from: { seq: start ?? 1 },\n generation: oldest.generation,\n tracker,\n overflowed: false,\n owner,\n group: null,\n claiming: false,\n };\n this.#topics.set(name, topic);\n return topic;\n }\n\n /**\n * Moves a held pattern to a new subscription. The topics it owned are\n * pointed at the new channel and generation and keep their trackers, so\n * each keeps the next `seq` it expects: the server sends nothing again\n * for topics the connection holds. The earlier channel ends; what it\n * still holds can be taken or dropped without any effect on the topics.\n * Acknowledgements held back for the earlier channel's full buffer are\n * sent now, because nothing will report those messages as taken to the\n * new subscription.\n *\n * @param pattern - The pattern, which must be held.\n * @param channel - The new subscription's channel.\n * @param generation - The new subscription.\n */\n #replacePattern(pattern: string, channel: Channel, generation: number): void {\n this.#patterns.get(pattern)?.channel.end();\n for (const [name, topic] of this.#topics) {\n if (topic.owner !== pattern) {\n continue;\n }\n topic.channel = channel;\n topic.generation = generation;\n for (const seq of topic.tracker.deferred) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n }\n topic.tracker.deferred.clear();\n }\n }\n\n /**\n * Claims every unclaimed topic of the session a pattern matches: each\n * stops being unclaimed and is tracked as owned by the pattern, with\n * `claiming` set until its own `subscribed` arrives.\n *\n * @param pattern - The pattern.\n * @param channel - The pattern's channel.\n * @param generation - The pattern's subscription.\n * @returns The claimed topics in name order, each of which needs a\n * subscribe by name with `from: \"resume\"`.\n */\n #claimMatching(pattern: string, channel: Channel, generation: number): string[] {\n const claimed = [...this.#unclaimed].filter((name) => matchesPattern(pattern, name)).sort();\n for (const name of claimed) {\n this.#unclaimed.delete(name);\n this.#topics.set(name, {\n channel,\n from: \"resume\",\n generation,\n tracker: new DeliveryTracker(),\n overflowed: false,\n owner: pattern,\n group: null,\n claiming: true,\n });\n }\n return claimed;\n }\n\n /**\n * Stops tracking a subscription and ends it: a topic subscribed by name,\n * or a wildcard pattern together with every topic joined through it.\n *\n * @param name - The topic or pattern.\n * @param generation - Only release it if it is still this subscription;\n * `null` releases whatever is there.\n * @returns What to unsubscribe from on the server: the name first, and\n * for a pattern the topics it owned. Empty when nothing was released.\n */\n #release(name: string, generation: number | null): string[] {\n const pattern = this.#patterns.get(name);\n if (pattern !== undefined && (generation === null || pattern.generation === generation)) {\n this.#patterns.delete(name);\n pattern.channel.end();\n const names = [name];\n for (const [topic, entry] of this.#topics) {\n if (entry.owner === name) {\n this.#topics.delete(topic);\n names.push(topic);\n }\n }\n return names;\n }\n const topic = this.#topics.get(name);\n if (topic?.owner === null && (generation === null || topic.generation === generation)) {\n this.#topics.delete(name);\n topic.channel.end();\n return [name];\n }\n return [];\n }\n\n /**\n * Unsubscribes without waiting, when the application closes a\n * subscription, if the topic or pattern still belongs to it. A pattern's\n * owned topics are unsubscribed with it.\n *\n * @param topic - The topic or pattern.\n * @param generation - The subscription being closed.\n */\n #forget(topic: string, generation: number): void {\n const released = this.#release(topic, generation);\n if (released.length === 0) {\n return;\n }\n this.#subscribeWaiters.get(topic)?.reject(PopSubError.closed(null));\n this.#subscribeWaiters.delete(topic);\n for (const name of released) {\n if (this.#connection === null) {\n this.#queueOffline({ type: \"unsubscribe\", topic: name });\n } else {\n this.#send({ type: \"unsubscribe\", topic: name }, this.#takeId());\n }\n }\n this.#wake?.();\n }\n\n /**\n * Called when the application takes a message: sends an acknowledgement\n * held back for a full buffer, and lets a paused client reconnect once\n * there is room.\n *\n * @param topic - The topic.\n * @param generation - The subscription the message came from.\n * @param message - The message taken.\n */\n #taken(topic: string, generation: number, message: Message): void {\n const entry = this.#topics.get(topic);\n if (entry?.generation === generation && entry.tracker.deferred.delete(message.seq)) {\n entry.tracker.acked.insert(message.seq);\n this.#send({ type: \"ack\", topic, seq: message.seq });\n }\n this.#wake?.();\n }\n\n /**\n * Parses a frame and acts on it; frames this client doesn't know are ignored.\n *\n * @param text - The frame's text.\n */\n #onText(text: string): void {\n const frame = parseServerFrame(text);\n if (frame !== null) {\n this.#onFrame(frame);\n }\n }\n\n /**\n * Acts on a frame from the server. A reply's pending entry is removed by\n * its id first, so a `pong` needs nothing more: hearing it at all is what\n * keeps the connection from being given up as silent. A `subscribed` for\n * a topic being claimed ends the claim and starts its next expected `seq`\n * over at `replay_from`.\n *\n * @param frame - The frame.\n */\n #onFrame(frame: ServerFrame): void {\n const id = typeof frame.id === \"number\" ? frame.id : null;\n const pending = id === null ? undefined : this.#pending.get(id);\n if (id !== null) {\n this.#pending.delete(id);\n }\n if (pending?.kind === \"request\") {\n if (frame.type === \"error\") {\n pending.settle.reject(\n PopSubError.server(errorCode(frame.code), frame.message, frame.retry_after ?? null),\n );\n } else {\n pending.settle.resolve(frame);\n }\n return;\n }\n const unprompted = frame.id === undefined || frame.id === null;\n switch (frame.type) {\n case \"message\":\n this.#deliver(frame);\n break;\n case \"subscribed\": {\n if (!this.#patterns.has(frame.topic)) {\n const tracked = this.#topics.get(frame.topic);\n if (tracked === undefined) {\n this.#adopt(frame.topic, frame.replay_from);\n } else {\n if (tracked.claiming) {\n tracked.claiming = false;\n tracked.tracker.nextExpected = null;\n }\n tracked.tracker.moveTo(frame.replay_from);\n }\n }\n const waiter = this.#subscribeWaiters.get(frame.topic);\n if (waiter !== undefined) {\n this.#subscribeWaiters.delete(frame.topic);\n waiter.resolve();\n }\n break;\n }\n case \"unsubscribed\":\n if (pending?.kind === \"unsubscribe\") {\n pending.settle.resolve();\n } else if (unprompted && this.#dropTopic(frame.topic)) {\n this.emitter.emit({ type: \"unsubscribed\", topic: frame.topic });\n }\n break;\n case \"published\":\n if (pending?.kind === \"publish\" && id !== null) {\n this.#unconfirmed.delete(id);\n pending.settle.resolve({ seq: frame.seq, messageId: frame.message_id });\n }\n break;\n case \"truncated\":\n this.#topics.get(frame.topic)?.tracker.moveTo(frame.first_available);\n this.emitter.emit({ type: \"truncated\", topic: frame.topic, firstAvailable: frame.first_available });\n break;\n case \"stalled\":\n this.emitter.emit({ type: \"stalled\", topic: frame.topic, seq: frame.seq });\n break;\n case \"auth_expiring\":\n this.emitter.emit({ type: \"authExpiring\", expiresAtMs: frame.expires_at_ms });\n if (\"password\" in this.#config.credentials) {\n const loginId = this.#takeId();\n this.#pending.set(loginId, { kind: \"relogin\" });\n const { username, password } = this.#config.credentials;\n this.#send({ type: \"login\", username, password }, loginId);\n } else if (\"tokenProvider\" in this.#config.credentials) {\n this.#renew(this.#config.credentials.tokenProvider);\n }\n break;\n case \"logged_in\":\n if (pending?.kind === \"relogin\") {\n const authId = this.#takeId();\n this.#pending.set(authId, { kind: \"reauth\" });\n this.#send({ type: \"auth\", token: frame.token, protocol: PROTOCOL_VERSION }, authId);\n }\n break;\n case \"authenticated\":\n if (pending?.kind === \"reauth\") {\n this.emitter.emit({ type: \"authRefreshed\" });\n }\n break;\n case \"pong\":\n break;\n case \"error\":\n this.#onError(pending, id, frame);\n break;\n default:\n break;\n }\n }\n\n /**\n * Routes an error frame to the request it answers, or to the events. A\n * refused subscribe ends that subscription; a refused resubscribe of a\n * topic owned by a pattern only stops tracking that topic.\n *\n * @param pending - The request it answers, if its id matched one.\n * @param id - Its request id, if it had one.\n * @param frame - The error frame.\n */\n #onError(\n pending: Pending | undefined,\n id: number | null,\n frame: Extract<ServerMessage, { type: \"error\" }>,\n ): void {\n const code = errorCode(frame.code);\n const error = PopSubError.server(code, frame.message, frame.retry_after ?? null);\n switch (pending?.kind) {\n case \"subscribe\": {\n const released = this.#release(pending.topic, pending.generation).length > 0;\n const owned = this.#topics.get(pending.topic);\n if (!released && owned?.owner != null && owned.generation === pending.generation) {\n this.#topics.delete(pending.topic);\n }\n if (released) {\n const waiter = this.#subscribeWaiters.get(pending.topic);\n this.#subscribeWaiters.delete(pending.topic);\n waiter?.reject(error);\n }\n break;\n }\n case \"unsubscribe\":\n pending.settle.reject(error);\n break;\n case \"publish\":\n if (id !== null) {\n this.#unconfirmed.delete(id);\n }\n pending.settle.reject(error);\n break;\n case \"ping\":\n break;\n default:\n this.emitter.emit({ type: \"serverError\", code, message: frame.message });\n break;\n }\n }\n\n /**\n * Hands a delivered message to its subscription, dropping duplicates,\n * acknowledging as the ack mode says, and holding back when the buffer is\n * full. A message for an untracked topic is adopted by the oldest\n * matching wildcard pattern; when none matches it is acknowledged and dropped.\n *\n * A message on a topic the server holds for the session that the\n * application hasn't subscribed to here, or whose subscribe is still\n * unanswered, is dropped without an acknowledgement: the server keeps it\n * and replays it when the application's subscribe is handled.\n *\n * @param delivery - The delivered message.\n */\n #deliver(delivery: Extract<ServerMessage, { type: \"message\" }>): void {\n const { topic: name, seq } = delivery;\n const qos: 0 | 1 = delivery.qos === 1 ? 1 : 0;\n if (this.#unclaimed.has(name)) {\n return;\n }\n const topic = this.#topics.get(name) ?? this.#adopt(name, null);\n if (topic === undefined) {\n if (qos === 1) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n if (topic.overflowed || topic.claiming) {\n return;\n }\n const automatic = this.#config.ackMode === \"auto\";\n if (topic.tracker.isDuplicate(seq)) {\n if (qos === 1 && topic.tracker.reacksDuplicate(seq, automatic)) {\n this.#send({ type: \"ack\", topic: name, seq });\n }\n return;\n }\n const buffered = topic.channel.size;\n if (buffered >= this.#config.subscriptionBuffer + this.#maxInflight) {\n topic.overflowed = true;\n this.#endServe?.({ kind: \"pause\" });\n return;\n }\n topic.tracker.accept(seq);\n let acker: (() => void) | null = null;\n if (qos === 1) {\n if (!automatic) {\n acker = () => {\n this.ack(name, seq);\n };\n } else if (buffered < this.#config.subscriptionBuffer) {\n topic.tracker.acked.insert(seq);\n this.#send({ type: \"ack\", topic: name, seq });\n } else {\n topic.tracker.deferred.add(seq);\n }\n }\n topic.channel.push(\n new Message(\n {\n topic: name,\n seq,\n messageId: delivery.message_id,\n payload: delivery.payload,\n encoding: delivery.encoding === \"base64\" ? \"base64\" : null,\n qos,\n publishedAtMs: delivery.published_at_ms,\n },\n acker,\n ),\n );\n }\n\n /**\n * Fails every admin request still waiting when a connection ends: the\n * server may or may not have carried it out. `ping`s, token refreshes and\n * subscribes of the old connection are forgotten; subscribes are sent\n * again by `#restore`.\n */\n #failRequests(): void {\n for (const [id, pending] of this.#pending) {\n if (pending.kind === \"request\") {\n this.#pending.delete(id);\n pending.settle.reject(\n new PopSubError(\n \"connect\",\n \"the connection dropped before the reply; the request may or may not have been carried out\",\n ),\n );\n } else if (\n pending.kind === \"ping\" ||\n pending.kind === \"relogin\" ||\n pending.kind === \"reauth\" ||\n pending.kind === \"subscribe\"\n ) {\n this.#pending.delete(id);\n }\n }\n }\n\n /**\n * Throws if the client has stopped.\n *\n * @throws PopSubError of kind `closed` with the close code that stopped it.\n */\n #throwIfStopped(): void {\n if (this.#stopped !== null) {\n throw PopSubError.closed(this.#stopped.code);\n }\n }\n\n /**\n * Stops the client for good: records why, fails everything waiting, ends\n * every subscription, and removes every event listener.\n *\n * @param code - The close code that stopped it, if any.\n * @param cause - The unexpected exception that stopped it, if any.\n */\n #stop(code: CloseCode | null, cause?: unknown): void {\n this.#endServe?.({ kind: \"stop\" });\n this.#wake = null;\n this.#stopped = { code };\n const error = PopSubError.closed(code);\n this.#ready?.reject(\n cause === undefined\n ? error\n : new PopSubError(\n \"closed\",\n `the client stopped unexpectedly: ${cause instanceof Error ? cause.message : \"unknown error\"}`,\n { cause },\n ),\n );\n this.#ready = null;\n for (const waiter of this.#subscribeWaiters.values()) {\n waiter.reject(error);\n }\n this.#subscribeWaiters.clear();\n for (const pending of this.#pending.values()) {\n if (pending.kind === \"unsubscribe\" || pending.kind === \"publish\" || pending.kind === \"request\") {\n pending.settle.reject(error);\n }\n }\n this.#pending.clear();\n this.#unconfirmed.clear();\n this.#offline = [];\n for (const topic of this.#topics.values()) {\n topic.channel.end();\n }\n this.#topics.clear();\n for (const pattern of this.#patterns.values()) {\n pattern.channel.end();\n }\n this.#patterns.clear();\n this.#unclaimed.clear();\n this.emitter.clear();\n this.#finish();\n }\n}\n\n/**\n * Calls a token provider and checks what it returns.\n *\n * @param provider - The token provider.\n * @returns The token.\n * @throws PopSubError of kind `connect` when the provider rejects or returns\n * something other than a non-empty string, so the attempt is retried.\n */\nasync function fetchToken(provider: () => Promise<string>): Promise<string> {\n let token: unknown;\n try {\n token = await provider();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new PopSubError(\"connect\", `the token provider failed: ${message}`, { cause: error });\n }\n if (typeof token !== \"string\" || token === \"\") {\n throw new PopSubError(\"connect\", \"the token provider returned no token\");\n }\n return token;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -25,9 +25,9 @@
|
|
|
25
25
|
*
|
|
26
26
|
* @module
|
|
27
27
|
*/
|
|
28
|
-
export { Admin, type TopicInfo, type User } from "./admin.js";
|
|
28
|
+
export { Admin, type BackupInfo, type TopicInfo, type User } from "./admin.js";
|
|
29
29
|
export { Client, type StartFrom } from "./client.js";
|
|
30
|
-
export type { AckMode, ClientConfig, Credentials, PasswordCredentials, ReconnectPolicy, TokenCredentials, } from "./config.js";
|
|
30
|
+
export type { AckMode, ClientConfig, Credentials, PasswordCredentials, ProviderCredentials, ReconnectPolicy, TokenCredentials, } from "./config.js";
|
|
31
31
|
export type { Published } from "./engine.js";
|
|
32
32
|
export { PopSubError, type ErrorKind } from "./errors.js";
|
|
33
33
|
export type { AuthExpiringEvent, AuthRefreshedEvent, ClientEvent, ClientEventListener, ConnectedEvent, DisconnectedEvent, ServerErrorEvent, StalledEvent, TruncatedEvent, UnsubscribedEvent, } from "./events.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,KAAK,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,KAAK,EAA8C,MAAM,YAAY,CAAC;AAC/E,OAAO,EAAE,MAAM,EAAkB,MAAM,aAAa,CAAC;AAWrD,OAAO,EAAE,WAAW,EAAkB,MAAM,aAAa,CAAC;AAa1D,OAAO,EACL,SAAS,EACT,WAAW,EACX,gBAAgB,GAOjB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC","sourcesContent":["/**\n * The PopSub client for browsers and Node.js 22 or later.\n *\n * ```ts\n * import { Client } from \"popsub\";\n *\n * const client = await Client.connect({\n * url: \"ws://127.0.0.1:8080\",\n * credentials: { username: \"alice\", password: \"secret-password\" },\n * sessionId: \"alice-laptop\",\n * });\n * const orders = await client.subscribe(\"orders\", \"resume\");\n * const stored = await client.publishConfirmed(\"orders\", \"order 42 shipped\");\n * client.publishBytes(\"orders\", new Uint8Array([0x00, 0xff]));\n * for await (const message of orders) {\n * console.log(message.topic, message.seq, message.payload);\n * }\n * ```\n *\n * A payload is a string. `publishBytes` and `publishBytesConfirmed` send a\n * body that isn't text as base64, and `Message.bytes` returns the bytes of\n * any message.\n *\n * The protocol is documented in the repository's `docs/DESIGN.md` section 4.\n *\n * @module\n */\n\nexport { Admin, type BackupInfo, type TopicInfo, type User } from \"./admin.js\";\nexport { Client, type StartFrom } from \"./client.js\";\nexport type {\n AckMode,\n ClientConfig,\n Credentials,\n PasswordCredentials,\n ProviderCredentials,\n ReconnectPolicy,\n TokenCredentials,\n} from \"./config.js\";\nexport type { Published } from \"./engine.js\";\nexport { PopSubError, type ErrorKind } from \"./errors.js\";\nexport type {\n AuthExpiringEvent,\n AuthRefreshedEvent,\n ClientEvent,\n ClientEventListener,\n ConnectedEvent,\n DisconnectedEvent,\n ServerErrorEvent,\n StalledEvent,\n TruncatedEvent,\n UnsubscribedEvent,\n} from \"./events.js\";\nexport {\n CloseCode,\n ERROR_CODES,\n PROTOCOL_VERSION,\n type Access,\n type Encoding,\n type ErrorCode,\n type RoleKind,\n type RoleSpec,\n type TopicGrant,\n} from \"./protocol.js\";\nexport { Message, Subscription } from \"./subscription.js\";\n"]}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -67,6 +67,21 @@ export interface WireTopicInfo {
|
|
|
67
67
|
/** How many live subscriptions it has. */
|
|
68
68
|
subscribers: number;
|
|
69
69
|
}
|
|
70
|
+
/** A backup as the server describes it in a `backup_created` frame. */
|
|
71
|
+
export interface WireBackupInfo {
|
|
72
|
+
/** The backup's directory name. */
|
|
73
|
+
name: string;
|
|
74
|
+
/** Where the backup is on the server's file system. */
|
|
75
|
+
path: string;
|
|
76
|
+
/** How many topics it holds. */
|
|
77
|
+
topics: number;
|
|
78
|
+
/** How many records it holds across every topic. */
|
|
79
|
+
records: number;
|
|
80
|
+
/** How many bytes were written. */
|
|
81
|
+
bytes: number;
|
|
82
|
+
/** Whether accounts were included. */
|
|
83
|
+
users: boolean;
|
|
84
|
+
}
|
|
70
85
|
/** The admin requests, which are never queued or resent. */
|
|
71
86
|
export type AdminRequest = {
|
|
72
87
|
type: "create_user";
|
|
@@ -110,6 +125,9 @@ export type AdminRequest = {
|
|
|
110
125
|
} | {
|
|
111
126
|
type: "purge_topic";
|
|
112
127
|
topic: string;
|
|
128
|
+
} | {
|
|
129
|
+
type: "backup";
|
|
130
|
+
name?: string;
|
|
113
131
|
};
|
|
114
132
|
/** Every frame this client sends, without its request id. */
|
|
115
133
|
export type ClientMessage = {
|
|
@@ -222,6 +240,9 @@ export type ServerMessage = {
|
|
|
222
240
|
} | {
|
|
223
241
|
type: "topics";
|
|
224
242
|
topics: WireTopicInfo[];
|
|
243
|
+
} | {
|
|
244
|
+
type: "backup_created";
|
|
245
|
+
backup: WireBackupInfo;
|
|
225
246
|
} | {
|
|
226
247
|
type: "error";
|
|
227
248
|
code: string;
|
|
@@ -233,7 +254,7 @@ export type ServerFrame = ServerMessage & {
|
|
|
233
254
|
id?: RequestId | null;
|
|
234
255
|
};
|
|
235
256
|
/** Every error code protocol version 1 defines. */
|
|
236
|
-
export declare const ERROR_CODES: readonly ["bad_request", "unauthenticated", "auth_failed", "invalid_credentials", "locked_out", "rate_limited", "not_authorized", "registration_failed", "invalid_session_id", "session_unavailable", "unsupported_protocol", "storage_unavailable", "payload_too_large", "invalid_topic", "forbidden", "user_not_found", "user_exists", "topic_not_found", "internal"];
|
|
257
|
+
export declare const ERROR_CODES: readonly ["bad_request", "unauthenticated", "auth_failed", "invalid_credentials", "locked_out", "rate_limited", "not_authorized", "registration_failed", "invalid_session_id", "session_unavailable", "unsupported_protocol", "storage_unavailable", "payload_too_large", "invalid_topic", "forbidden", "user_not_found", "user_exists", "topic_not_found", "backup_exists", "backup_unsupported", "topic_limit_reached", "internal"];
|
|
237
258
|
/** Why the server refused a request. */
|
|
238
259
|
export type ErrorCode = (typeof ERROR_CODES)[number];
|
|
239
260
|
/**
|
package/dist/protocol.js
CHANGED
|
@@ -30,6 +30,9 @@ export const ERROR_CODES = [
|
|
|
30
30
|
"user_not_found",
|
|
31
31
|
"user_exists",
|
|
32
32
|
"topic_not_found",
|
|
33
|
+
"backup_exists",
|
|
34
|
+
"backup_unsupported",
|
|
35
|
+
"topic_limit_reached",
|
|
33
36
|
"internal",
|
|
34
37
|
];
|
|
35
38
|
/** The codes `errorCode` recognises, for fast lookup. */
|
|
@@ -109,6 +112,7 @@ const REQUIRED_FIELDS = {
|
|
|
109
112
|
pong: {},
|
|
110
113
|
topic_info: { topic: "object" },
|
|
111
114
|
topics: { topics: "object" },
|
|
115
|
+
backup_created: { backup: "object" },
|
|
112
116
|
error: { code: "string", message: "string" },
|
|
113
117
|
};
|
|
114
118
|
/**
|
package/dist/protocol.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,qEAAqE;AACrE,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AA6JlC,mDAAmD;AACnD,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,aAAa;IACb,iBAAiB;IACjB,aAAa;IACb,qBAAqB;IACrB,YAAY;IACZ,cAAc;IACd,gBAAgB;IAChB,qBAAqB;IACrB,oBAAoB;IACpB,qBAAqB;IACrB,sBAAsB;IACtB,qBAAqB;IACrB,mBAAmB;IACnB,eAAe;IACf,WAAW;IACX,gBAAgB;IAChB,aAAa;IACb,iBAAiB;IACjB,UAAU;CACF,CAAC;AAKX,yDAAyD;AACzD,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,GAAY;IACpC,OAAO,OAAO,GAAG,KAAK,QAAQ,IAAI,iBAAiB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,GAAiB,CAAC,CAAC,CAAC,UAAU,CAAC;AACjG,CAAC;AAED,gEAAgE;AAChE,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,SAAS,EAAE,IAAI;IACf,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,aAAa,EAAE,IAAI;IACnB,UAAU,EAAE,IAAI;IAChB,eAAe,EAAE,IAAI;IACrB,gBAAgB,EAAE,IAAI;IACtB,YAAY,EAAE,IA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AC;IAChE,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;QACrD,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;QAC9B,IAAI,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;YAChD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,MAAgC,CAAC;AAC1C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,YAAY,CAC1B,KAAa,EACb,OAAe,EACf,QAAyB;IAEzB,OAAO,QAAQ,KAAK,IAAI;QACtB,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE;QACrC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AACpD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,WAAW,CAAC,OAAsB,EAAE,EAAc;IAChE,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/**\n * The PopSub wire protocol, version 1: the JSON frames a client sends and\n * receives, the error codes and the WebSocket close codes, as described in\n * `docs/DESIGN.md` section 4 and `docs/protocol/*.json`.\n *\n * These types keep the protocol's own snake_case field names. The public\n * API converts them to camelCase at its edges.\n *\n * @module\n */\n\n/** The protocol version this client speaks, sent in every `auth`. */\nexport const PROTOCOL_VERSION = 1;\n\n/** A request id. This client only ever sends numbers. */\nexport type RequestId = number | string;\n\n/** Where replay starts when subscribing, as it is written on the wire. */\nexport type WireStartFrom = \"resume\" | \"new\" | { last: number } | { since_ms: number } | { seq: number };\n\n/**\n * How a payload string encodes a message's bytes when it isn't text.\n * `base64` is standard padded base64; a frame without an encoding carries text.\n */\nexport type Encoding = \"base64\";\n\n/** What a topic grant allows. */\nexport type Access = \"subscribe\" | \"publish\" | \"both\";\n\n/** The kind of account. */\nexport type RoleKind = \"admin\" | \"user\" | \"readonly\";\n\n/** One topic pattern an account may use, and how. */\nexport interface TopicGrant {\n /** The topic pattern, such as `orders/#`. */\n pattern: string;\n /** What the pattern allows. */\n access: Access;\n}\n\n/** What an account may do. `topics` is ignored for admins. */\nexport interface RoleSpec {\n /** The kind of account. */\n kind: RoleKind;\n /** The account's topic grants. */\n topics?: TopicGrant[];\n}\n\n/** An account as the server describes it in `user` and `users` frames. */\nexport interface WireUser {\n /** The username. */\n username: string;\n /** What it may do. */\n role: RoleSpec;\n /** Whether it may log in and use topics. */\n enabled: boolean;\n /** When it was created, in milliseconds since the Unix epoch. */\n created_at_ms: number;\n}\n\n/** A topic as the server describes it in `topic_info` and `topics` frames. */\nexport interface WireTopicInfo {\n /** The topic's name. */\n name: string;\n /** The oldest `seq` still kept, or `last_seq + 1` when nothing is kept. */\n first_seq: number;\n /** The newest `seq` ever published. */\n last_seq: number;\n /** How many records are kept now. */\n messages: number;\n /** How many live subscriptions it has. */\n subscribers: number;\n}\n\n/** The admin requests, which are never queued or resent. */\nexport type AdminRequest =\n | { type: \"create_user\"; username: string; password: string; role: RoleSpec }\n | { type: \"get_user\"; username: string }\n | { type: \"list_users\" }\n | { type: \"set_role\"; username: string; role: RoleSpec }\n | { type: \"grant\"; username: string; pattern: string; access: Access }\n | { type: \"revoke\"; username: string; pattern: string }\n | { type: \"set_password\"; username: string; password: string }\n | { type: \"set_enabled\"; username: string; enabled: boolean }\n | { type: \"delete_user\"; username: string }\n | { type: \"list_topics\" }\n | { type: \"get_topic\"; topic: string }\n | { type: \"purge_topic\"; topic: string };\n\n/** Every frame this client sends, without its request id. */\nexport type ClientMessage =\n | { type: \"login\"; username: string; password: string }\n | {\n type: \"auth\";\n token: string;\n protocol?: number;\n session_id?: string;\n clean_start?: boolean;\n hold_resumed?: boolean;\n }\n | { type: \"subscribe\"; topic: string; from?: WireStartFrom; group?: string }\n | { type: \"unsubscribe\"; topic: string }\n | {\n type: \"publish\";\n topic: string;\n payload: string;\n encoding?: Encoding;\n message_id?: string;\n qos?: 0 | 1;\n }\n | { type: \"ack\"; topic: string; seq: number }\n | { type: \"ping\" }\n | AdminRequest;\n\n/** The limits a server announces in `authenticated`. */\nexport interface Limits {\n /** How many QoS 1 records each subscription may have unacknowledged. */\n max_inflight: number;\n /** How long an untouched durable session is kept, in seconds. */\n session_expiry_secs: number;\n /** How often the server pings, in seconds. */\n heartbeat_secs: number;\n /** How long the server waits for anything from the client, in seconds. */\n idle_timeout_secs: number;\n /** The largest payload the server accepts, in bytes. */\n max_payload_bytes: number;\n /** The longest topic name, in bytes. */\n max_topic_bytes: number;\n}\n\n/** Every frame the server sends that this client reads, without its id. */\nexport type ServerMessage =\n | { type: \"registered\" }\n | { type: \"logged_in\"; token: string }\n | {\n type: \"authenticated\";\n protocol: number;\n limits: Limits;\n session_id?: string | null;\n resumed?: string[];\n held?: boolean;\n }\n | { type: \"subscribed\"; topic: string; replay_from: number; replay_to: number }\n | { type: \"unsubscribed\"; topic: string }\n | { type: \"published\"; message_id: string; seq: number }\n | {\n type: \"message\";\n topic: string;\n seq: number;\n message_id: string;\n payload: string;\n encoding?: Encoding | null;\n qos: number;\n published_at_ms: number;\n }\n | { type: \"truncated\"; topic: string; first_available: number }\n | { type: \"stalled\"; topic: string; seq: number }\n | { type: \"auth_expiring\"; expires_at_ms: number }\n | { type: \"user\"; user: WireUser }\n | { type: \"users\"; users: WireUser[] }\n | { type: \"user_deleted\"; username: string }\n | { type: \"pong\" }\n | { type: \"topic_info\"; topic: WireTopicInfo }\n | { type: \"topics\"; topics: WireTopicInfo[] }\n | { type: \"error\"; code: string; message: string; retry_after?: number | null };\n\n/** A server frame: a message plus the id of the request it answers, if any. */\nexport type ServerFrame = ServerMessage & { id?: RequestId | null };\n\n/** Every error code protocol version 1 defines. */\nexport const ERROR_CODES = [\n \"bad_request\",\n \"unauthenticated\",\n \"auth_failed\",\n \"invalid_credentials\",\n \"locked_out\",\n \"rate_limited\",\n \"not_authorized\",\n \"registration_failed\",\n \"invalid_session_id\",\n \"session_unavailable\",\n \"unsupported_protocol\",\n \"storage_unavailable\",\n \"payload_too_large\",\n \"invalid_topic\",\n \"forbidden\",\n \"user_not_found\",\n \"user_exists\",\n \"topic_not_found\",\n \"internal\",\n] as const;\n\n/** Why the server refused a request. */\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/** The codes `errorCode` recognises, for fast lookup. */\nconst KNOWN_ERROR_CODES: ReadonlySet<string> = new Set(ERROR_CODES);\n\n/**\n * Reads an error code from a frame. The protocol says to treat a code this\n * client doesn't know like `internal`.\n *\n * @param raw - The `code` field as received.\n * @returns The code, or `internal` when it is unknown.\n */\nexport function errorCode(raw: unknown): ErrorCode {\n return typeof raw === \"string\" && KNOWN_ERROR_CODES.has(raw) ? (raw as ErrorCode) : \"internal\";\n}\n\n/** The WebSocket close codes a PopSub server sends, by name. */\nexport const CloseCode = {\n GoingAway: 1001,\n MessageTooBig: 1009,\n InternalError: 1011,\n TryAgainLater: 1013,\n AuthFailed: 4001,\n Unauthenticated: 4002,\n SessionTakenOver: 4003,\n TokenExpired: 4004,\n IdleTimeout: 4005,\n UnsupportedProtocol: 4006,\n SessionUnavailable: 4007,\n SlowConsumer: 4008,\n AccountDisabled: 4009,\n} as const;\n\n/** One of the close codes a PopSub server sends. */\nexport type CloseCode = (typeof CloseCode)[keyof typeof CloseCode];\n\n/** The close codes `closeCode` recognises. */\nconst KNOWN_CLOSE_CODES: ReadonlySet<number> = new Set(Object.values(CloseCode));\n\n/** The close codes after which the client never reconnects on its own. */\nconst FINAL_CLOSE_CODES: ReadonlySet<number> = new Set([\n CloseCode.AuthFailed,\n CloseCode.SessionTakenOver,\n CloseCode.UnsupportedProtocol,\n CloseCode.AccountDisabled,\n]);\n\n/**\n * Reads a close code from a WebSocket close event.\n *\n * @param raw - The close event's code.\n * @returns The PopSub close code, or `null` for any other code, such as\n * 1006 when the connection dropped without a close frame.\n */\nexport function closeCode(raw: number): CloseCode | null {\n return KNOWN_CLOSE_CODES.has(raw) ? (raw as CloseCode) : null;\n}\n\n/**\n * Whether a close code allows reconnecting, by the table in\n * `docs/protocol/close-codes.json`. The client adds one rule on top: after\n * `TokenExpired` it reconnects only with password credentials.\n *\n * @param code - The close code.\n * @returns False for `AuthFailed`, `SessionTakenOver`,\n * `UnsupportedProtocol` and `AccountDisabled`, true otherwise.\n */\nexport function shouldReconnect(code: CloseCode): boolean {\n return !FINAL_CLOSE_CODES.has(code);\n}\n\n/** The fields each known server frame type must have, with their types. */\nconst REQUIRED_FIELDS: Readonly<Record<ServerMessage[\"type\"], Readonly<Record<string, string>>>> = {\n registered: {},\n logged_in: { token: \"string\" },\n authenticated: { limits: \"object\" },\n subscribed: { topic: \"string\", replay_from: \"number\" },\n unsubscribed: { topic: \"string\" },\n published: { message_id: \"string\", seq: \"number\" },\n message: { topic: \"string\", seq: \"number\", message_id: \"string\", payload: \"string\", qos: \"number\" },\n truncated: { topic: \"string\", first_available: \"number\" },\n stalled: { topic: \"string\", seq: \"number\" },\n auth_expiring: { expires_at_ms: \"number\" },\n user: { user: \"object\" },\n users: { users: \"object\" },\n user_deleted: { username: \"string\" },\n pong: {},\n topic_info: { topic: \"object\" },\n topics: { topics: \"object\" },\n error: { code: \"string\", message: \"string\" },\n};\n\n/**\n * Parses a text frame from the server.\n *\n * Frames that aren't JSON objects, have a `type` this client doesn't know,\n * or miss a field the client reads are ignored, as the protocol asks of\n * clients for frame types added later.\n *\n * @param text - The frame's text.\n * @returns The frame, or `null` when it should be ignored.\n */\nexport function parseServerFrame(text: string): ServerFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const type = record.type;\n if (typeof type !== \"string\" || !Object.hasOwn(REQUIRED_FIELDS, type)) {\n return null;\n }\n const required = REQUIRED_FIELDS[type as ServerMessage[\"type\"]];\n for (const [field, kind] of Object.entries(required)) {\n const present = record[field];\n if (typeof present !== kind || present === null) {\n return null;\n }\n }\n return record as unknown as ServerFrame;\n}\n\n/**\n * Builds a QoS 0 `publish` frame. A text publish carries no `encoding`\n * field at all, which is what a server reads as text.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @returns The frame.\n */\nexport function publishFrame(\n topic: string,\n payload: string,\n encoding: Encoding | null,\n): Extract<ClientMessage, { type: \"publish\" }> {\n return encoding === null\n ? { type: \"publish\", topic, payload }\n : { type: \"publish\", topic, payload, encoding };\n}\n\n/**\n * Writes a frame as JSON text.\n *\n * @param message - The frame.\n * @param id - The request id, when a reply is expected.\n * @returns The JSON text.\n */\nexport function encodeFrame(message: ClientMessage, id?: RequestId): string {\n return JSON.stringify(id === undefined ? message : { ...message, id });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,qEAAqE;AACrE,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AA+KlC,mDAAmD;AACnD,MAAM,CAAC,MAAM,WAAW,GAAG;IACzB,aAAa;IACb,iBAAiB;IACjB,aAAa;IACb,qBAAqB;IACrB,YAAY;IACZ,cAAc;IACd,gBAAgB;IAChB,qBAAqB;IACrB,oBAAoB;IACpB,qBAAqB;IACrB,sBAAsB;IACtB,qBAAqB;IACrB,mBAAmB;IACnB,eAAe;IACf,WAAW;IACX,gBAAgB;IAChB,aAAa;IACb,iBAAiB;IACjB,eAAe;IACf,oBAAoB;IACpB,qBAAqB;IACrB,UAAU;CACF,CAAC;AAKX,yDAAyD;AACzD,MAAM,iBAAiB,GAAwB,IAAI,GAAG,CA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AAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["/**\n * The PopSub wire protocol, version 1: the JSON frames a client sends and\n * receives, the error codes and the WebSocket close codes, as described in\n * `docs/DESIGN.md` section 4 and `docs/protocol/*.json`.\n *\n * These types keep the protocol's own snake_case field names. The public\n * API converts them to camelCase at its edges.\n *\n * @module\n */\n\n/** The protocol version this client speaks, sent in every `auth`. */\nexport const PROTOCOL_VERSION = 1;\n\n/** A request id. This client only ever sends numbers. */\nexport type RequestId = number | string;\n\n/** Where replay starts when subscribing, as it is written on the wire. */\nexport type WireStartFrom = \"resume\" | \"new\" | { last: number } | { since_ms: number } | { seq: number };\n\n/**\n * How a payload string encodes a message's bytes when it isn't text.\n * `base64` is standard padded base64; a frame without an encoding carries text.\n */\nexport type Encoding = \"base64\";\n\n/** What a topic grant allows. */\nexport type Access = \"subscribe\" | \"publish\" | \"both\";\n\n/** The kind of account. */\nexport type RoleKind = \"admin\" | \"user\" | \"readonly\";\n\n/** One topic pattern an account may use, and how. */\nexport interface TopicGrant {\n /** The topic pattern, such as `orders/#`. */\n pattern: string;\n /** What the pattern allows. */\n access: Access;\n}\n\n/** What an account may do. `topics` is ignored for admins. */\nexport interface RoleSpec {\n /** The kind of account. */\n kind: RoleKind;\n /** The account's topic grants. */\n topics?: TopicGrant[];\n}\n\n/** An account as the server describes it in `user` and `users` frames. */\nexport interface WireUser {\n /** The username. */\n username: string;\n /** What it may do. */\n role: RoleSpec;\n /** Whether it may log in and use topics. */\n enabled: boolean;\n /** When it was created, in milliseconds since the Unix epoch. */\n created_at_ms: number;\n}\n\n/** A topic as the server describes it in `topic_info` and `topics` frames. */\nexport interface WireTopicInfo {\n /** The topic's name. */\n name: string;\n /** The oldest `seq` still kept, or `last_seq + 1` when nothing is kept. */\n first_seq: number;\n /** The newest `seq` ever published. */\n last_seq: number;\n /** How many records are kept now. */\n messages: number;\n /** How many live subscriptions it has. */\n subscribers: number;\n}\n\n/** A backup as the server describes it in a `backup_created` frame. */\nexport interface WireBackupInfo {\n /** The backup's directory name. */\n name: string;\n /** Where the backup is on the server's file system. */\n path: string;\n /** How many topics it holds. */\n topics: number;\n /** How many records it holds across every topic. */\n records: number;\n /** How many bytes were written. */\n bytes: number;\n /** Whether accounts were included. */\n users: boolean;\n}\n\n/** The admin requests, which are never queued or resent. */\nexport type AdminRequest =\n | { type: \"create_user\"; username: string; password: string; role: RoleSpec }\n | { type: \"get_user\"; username: string }\n | { type: \"list_users\" }\n | { type: \"set_role\"; username: string; role: RoleSpec }\n | { type: \"grant\"; username: string; pattern: string; access: Access }\n | { type: \"revoke\"; username: string; pattern: string }\n | { type: \"set_password\"; username: string; password: string }\n | { type: \"set_enabled\"; username: string; enabled: boolean }\n | { type: \"delete_user\"; username: string }\n | { type: \"list_topics\" }\n | { type: \"get_topic\"; topic: string }\n | { type: \"purge_topic\"; topic: string }\n | { type: \"backup\"; name?: string };\n\n/** Every frame this client sends, without its request id. */\nexport type ClientMessage =\n | { type: \"login\"; username: string; password: string }\n | {\n type: \"auth\";\n token: string;\n protocol?: number;\n session_id?: string;\n clean_start?: boolean;\n hold_resumed?: boolean;\n }\n | { type: \"subscribe\"; topic: string; from?: WireStartFrom; group?: string }\n | { type: \"unsubscribe\"; topic: string }\n | {\n type: \"publish\";\n topic: string;\n payload: string;\n encoding?: Encoding;\n message_id?: string;\n qos?: 0 | 1;\n }\n | { type: \"ack\"; topic: string; seq: number }\n | { type: \"ping\" }\n | AdminRequest;\n\n/** The limits a server announces in `authenticated`. */\nexport interface Limits {\n /** How many QoS 1 records each subscription may have unacknowledged. */\n max_inflight: number;\n /** How long an untouched durable session is kept, in seconds. */\n session_expiry_secs: number;\n /** How often the server pings, in seconds. */\n heartbeat_secs: number;\n /** How long the server waits for anything from the client, in seconds. */\n idle_timeout_secs: number;\n /** The largest payload the server accepts, in bytes. */\n max_payload_bytes: number;\n /** The longest topic name, in bytes. */\n max_topic_bytes: number;\n}\n\n/** Every frame the server sends that this client reads, without its id. */\nexport type ServerMessage =\n | { type: \"registered\" }\n | { type: \"logged_in\"; token: string }\n | {\n type: \"authenticated\";\n protocol: number;\n limits: Limits;\n session_id?: string | null;\n resumed?: string[];\n held?: boolean;\n }\n | { type: \"subscribed\"; topic: string; replay_from: number; replay_to: number }\n | { type: \"unsubscribed\"; topic: string }\n | { type: \"published\"; message_id: string; seq: number }\n | {\n type: \"message\";\n topic: string;\n seq: number;\n message_id: string;\n payload: string;\n encoding?: Encoding | null;\n qos: number;\n published_at_ms: number;\n }\n | { type: \"truncated\"; topic: string; first_available: number }\n | { type: \"stalled\"; topic: string; seq: number }\n | { type: \"auth_expiring\"; expires_at_ms: number }\n | { type: \"user\"; user: WireUser }\n | { type: \"users\"; users: WireUser[] }\n | { type: \"user_deleted\"; username: string }\n | { type: \"pong\" }\n | { type: \"topic_info\"; topic: WireTopicInfo }\n | { type: \"topics\"; topics: WireTopicInfo[] }\n | { type: \"backup_created\"; backup: WireBackupInfo }\n | { type: \"error\"; code: string; message: string; retry_after?: number | null };\n\n/** A server frame: a message plus the id of the request it answers, if any. */\nexport type ServerFrame = ServerMessage & { id?: RequestId | null };\n\n/** Every error code protocol version 1 defines. */\nexport const ERROR_CODES = [\n \"bad_request\",\n \"unauthenticated\",\n \"auth_failed\",\n \"invalid_credentials\",\n \"locked_out\",\n \"rate_limited\",\n \"not_authorized\",\n \"registration_failed\",\n \"invalid_session_id\",\n \"session_unavailable\",\n \"unsupported_protocol\",\n \"storage_unavailable\",\n \"payload_too_large\",\n \"invalid_topic\",\n \"forbidden\",\n \"user_not_found\",\n \"user_exists\",\n \"topic_not_found\",\n \"backup_exists\",\n \"backup_unsupported\",\n \"topic_limit_reached\",\n \"internal\",\n] as const;\n\n/** Why the server refused a request. */\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\n/** The codes `errorCode` recognises, for fast lookup. */\nconst KNOWN_ERROR_CODES: ReadonlySet<string> = new Set(ERROR_CODES);\n\n/**\n * Reads an error code from a frame. The protocol says to treat a code this\n * client doesn't know like `internal`.\n *\n * @param raw - The `code` field as received.\n * @returns The code, or `internal` when it is unknown.\n */\nexport function errorCode(raw: unknown): ErrorCode {\n return typeof raw === \"string\" && KNOWN_ERROR_CODES.has(raw) ? (raw as ErrorCode) : \"internal\";\n}\n\n/** The WebSocket close codes a PopSub server sends, by name. */\nexport const CloseCode = {\n GoingAway: 1001,\n MessageTooBig: 1009,\n InternalError: 1011,\n TryAgainLater: 1013,\n AuthFailed: 4001,\n Unauthenticated: 4002,\n SessionTakenOver: 4003,\n TokenExpired: 4004,\n IdleTimeout: 4005,\n UnsupportedProtocol: 4006,\n SessionUnavailable: 4007,\n SlowConsumer: 4008,\n AccountDisabled: 4009,\n} as const;\n\n/** One of the close codes a PopSub server sends. */\nexport type CloseCode = (typeof CloseCode)[keyof typeof CloseCode];\n\n/** The close codes `closeCode` recognises. */\nconst KNOWN_CLOSE_CODES: ReadonlySet<number> = new Set(Object.values(CloseCode));\n\n/** The close codes after which the client never reconnects on its own. */\nconst FINAL_CLOSE_CODES: ReadonlySet<number> = new Set([\n CloseCode.AuthFailed,\n CloseCode.SessionTakenOver,\n CloseCode.UnsupportedProtocol,\n CloseCode.AccountDisabled,\n]);\n\n/**\n * Reads a close code from a WebSocket close event.\n *\n * @param raw - The close event's code.\n * @returns The PopSub close code, or `null` for any other code, such as\n * 1006 when the connection dropped without a close frame.\n */\nexport function closeCode(raw: number): CloseCode | null {\n return KNOWN_CLOSE_CODES.has(raw) ? (raw as CloseCode) : null;\n}\n\n/**\n * Whether a close code allows reconnecting, by the table in\n * `docs/protocol/close-codes.json`. The client adds one rule on top: after\n * `TokenExpired` it reconnects only with password credentials.\n *\n * @param code - The close code.\n * @returns False for `AuthFailed`, `SessionTakenOver`,\n * `UnsupportedProtocol` and `AccountDisabled`, true otherwise.\n */\nexport function shouldReconnect(code: CloseCode): boolean {\n return !FINAL_CLOSE_CODES.has(code);\n}\n\n/** The fields each known server frame type must have, with their types. */\nconst REQUIRED_FIELDS: Readonly<Record<ServerMessage[\"type\"], Readonly<Record<string, string>>>> = {\n registered: {},\n logged_in: { token: \"string\" },\n authenticated: { limits: \"object\" },\n subscribed: { topic: \"string\", replay_from: \"number\" },\n unsubscribed: { topic: \"string\" },\n published: { message_id: \"string\", seq: \"number\" },\n message: { topic: \"string\", seq: \"number\", message_id: \"string\", payload: \"string\", qos: \"number\" },\n truncated: { topic: \"string\", first_available: \"number\" },\n stalled: { topic: \"string\", seq: \"number\" },\n auth_expiring: { expires_at_ms: \"number\" },\n user: { user: \"object\" },\n users: { users: \"object\" },\n user_deleted: { username: \"string\" },\n pong: {},\n topic_info: { topic: \"object\" },\n topics: { topics: \"object\" },\n backup_created: { backup: \"object\" },\n error: { code: \"string\", message: \"string\" },\n};\n\n/**\n * Parses a text frame from the server.\n *\n * Frames that aren't JSON objects, have a `type` this client doesn't know,\n * or miss a field the client reads are ignored, as the protocol asks of\n * clients for frame types added later.\n *\n * @param text - The frame's text.\n * @returns The frame, or `null` when it should be ignored.\n */\nexport function parseServerFrame(text: string): ServerFrame | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value as Record<string, unknown>;\n const type = record.type;\n if (typeof type !== \"string\" || !Object.hasOwn(REQUIRED_FIELDS, type)) {\n return null;\n }\n const required = REQUIRED_FIELDS[type as ServerMessage[\"type\"]];\n for (const [field, kind] of Object.entries(required)) {\n const present = record[field];\n if (typeof present !== kind || present === null) {\n return null;\n }\n }\n return record as unknown as ServerFrame;\n}\n\n/**\n * Builds a QoS 0 `publish` frame. A text publish carries no `encoding`\n * field at all, which is what a server reads as text.\n *\n * @param topic - The topic.\n * @param payload - The body: text, or base64 when `encoding` says so.\n * @param encoding - How `payload` encodes the body, or `null` for text.\n * @returns The frame.\n */\nexport function publishFrame(\n topic: string,\n payload: string,\n encoding: Encoding | null,\n): Extract<ClientMessage, { type: \"publish\" }> {\n return encoding === null\n ? { type: \"publish\", topic, payload }\n : { type: \"publish\", topic, payload, encoding };\n}\n\n/**\n * Writes a frame as JSON text.\n *\n * @param message - The frame.\n * @param id - The request id, when a reply is expected.\n * @returns The JSON text.\n */\nexport function encodeFrame(message: ClientMessage, id?: RequestId): string {\n return JSON.stringify(id === undefined ? message : { ...message, id });\n}\n"]}
|
package/package.json
CHANGED