popsub 0.0.0-stage → 0.2.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/dist/admin.js ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * `Admin`, the account management requests, for clients logged in as an
3
+ * admin.
4
+ *
5
+ * Each call is one request and its reply. None is queued while the client
6
+ * is disconnected or resent after a reconnect, because repeating a change
7
+ * such as `createUser` isn't safe: a call made while disconnected fails
8
+ * with a `connect` error, and so does one whose connection drops before the
9
+ * reply, whether or not the server carried it out.
10
+ *
11
+ * @module
12
+ */
13
+ import { PopSubError } from "./errors.js";
14
+ /**
15
+ * Converts a topic from its wire form.
16
+ *
17
+ * @param topic - The topic as the server sent it.
18
+ * @returns The topic.
19
+ */
20
+ function topicFromWire(topic) {
21
+ return {
22
+ name: topic.name,
23
+ firstSeq: topic.first_seq,
24
+ lastSeq: topic.last_seq,
25
+ messages: topic.messages,
26
+ subscribers: topic.subscribers,
27
+ };
28
+ }
29
+ /**
30
+ * Converts an account from its wire form.
31
+ *
32
+ * @param user - The account as the server sent it.
33
+ * @returns The account.
34
+ */
35
+ function fromWire(user) {
36
+ return {
37
+ username: user.username,
38
+ role: user.role,
39
+ enabled: user.enabled,
40
+ createdAtMs: user.created_at_ms,
41
+ };
42
+ }
43
+ /**
44
+ * Builds the error for a reply of the wrong type.
45
+ *
46
+ * @param reply - What the server sent.
47
+ * @param expected - The type that was expected.
48
+ * @returns The `protocol` error.
49
+ */
50
+ function unexpected(reply, expected) {
51
+ return new PopSubError("protocol", `expected a ${expected} reply, got ${reply.type}`);
52
+ }
53
+ /**
54
+ * The admin requests, from `Client.admin`. Every call rejects with a
55
+ * `server` error with code `forbidden` unless the client is logged in as
56
+ * an enabled admin, `connect` when disconnected or when the connection
57
+ * drops before the reply, `timeout` when no reply arrives in time, and
58
+ * `closed` when the client has stopped.
59
+ */
60
+ export class Admin {
61
+ /** Sends the requests. */
62
+ #send;
63
+ /**
64
+ * Wraps a transport. Applications get an `Admin` from `Client.admin`.
65
+ *
66
+ * @param send - Sends one request and returns its reply.
67
+ */
68
+ constructor(send) {
69
+ this.#send = send;
70
+ }
71
+ /**
72
+ * Creates an account.
73
+ *
74
+ * @param username - Its name: 3 to 32 letters, digits, `_`, `.` or `-`.
75
+ * @param password - Its password, at least 8 characters.
76
+ * @param role - What it may do.
77
+ * @returns The new account.
78
+ * @throws PopSubError with code `user_exists`, or `bad_request` for an
79
+ * invalid name, password or pattern.
80
+ */
81
+ createUser(username, password, role) {
82
+ return this.#user({ type: "create_user", username, password, role });
83
+ }
84
+ /**
85
+ * Reads an account.
86
+ *
87
+ * @param username - The account.
88
+ * @returns The account.
89
+ * @throws PopSubError with code `user_not_found`.
90
+ */
91
+ getUser(username) {
92
+ return this.#user({ type: "get_user", username });
93
+ }
94
+ /**
95
+ * Lists every account, sorted by name.
96
+ *
97
+ * @returns The accounts.
98
+ * @throws PopSubError of kind `protocol` when the server answers with
99
+ * something other than `users`.
100
+ */
101
+ async listUsers() {
102
+ const reply = await this.#send({ type: "list_users" });
103
+ if (reply.type !== "users") {
104
+ throw unexpected(reply, "users");
105
+ }
106
+ return reply.users.map(fromWire);
107
+ }
108
+ /**
109
+ * Replaces an account's role. Live subscriptions the new role doesn't
110
+ * allow are ended.
111
+ *
112
+ * @param username - The account.
113
+ * @param role - Its new role.
114
+ * @returns The account as it now stands.
115
+ * @throws PopSubError with code `user_not_found`, or `bad_request` for an
116
+ * invalid pattern or for demoting the last enabled admin.
117
+ */
118
+ setRole(username, role) {
119
+ return this.#user({ type: "set_role", username, role });
120
+ }
121
+ /**
122
+ * Grants an account a topic pattern, replacing any grant it already has
123
+ * for exactly that pattern.
124
+ *
125
+ * @param username - The account.
126
+ * @param pattern - The topic pattern.
127
+ * @param access - What it allows.
128
+ * @returns The account as it now stands.
129
+ * @throws PopSubError with code `user_not_found`, or `bad_request` for an
130
+ * invalid pattern, an admin account, or publishing for a readonly one.
131
+ */
132
+ grant(username, pattern, access) {
133
+ return this.#user({ type: "grant", username, pattern, access });
134
+ }
135
+ /**
136
+ * Removes one of an account's grants. Live subscriptions no longer
137
+ * allowed are ended.
138
+ *
139
+ * @param username - The account.
140
+ * @param pattern - The pattern, exactly as granted.
141
+ * @returns The account as it now stands.
142
+ * @throws PopSubError with code `user_not_found`, or `bad_request` when
143
+ * the account has no such grant.
144
+ */
145
+ revoke(username, pattern) {
146
+ return this.#user({ type: "revoke", username, pattern });
147
+ }
148
+ /**
149
+ * Sets an account's password. Tokens issued before it are cancelled, and
150
+ * the account's connections are closed so they log in again.
151
+ *
152
+ * @param username - The account.
153
+ * @param password - The new password.
154
+ * @returns The account.
155
+ * @throws PopSubError with code `user_not_found`, or `bad_request` for a
156
+ * password that is too short or too long.
157
+ */
158
+ setPassword(username, password) {
159
+ return this.#user({ type: "set_password", username, password });
160
+ }
161
+ /**
162
+ * Enables or disables an account. Disabling closes its connections with
163
+ * `account_disabled` (4009) and refuses its logins and tokens.
164
+ *
165
+ * @param username - The account.
166
+ * @param enabled - Whether it may log in.
167
+ * @returns The account as it now stands.
168
+ * @throws PopSubError with code `user_not_found`, or `bad_request` for
169
+ * disabling the last enabled admin.
170
+ */
171
+ setEnabled(username, enabled) {
172
+ return this.#user({ type: "set_enabled", username, enabled });
173
+ }
174
+ /**
175
+ * Deletes an account and closes its connections with `account_disabled` (4009).
176
+ *
177
+ * @param username - The account.
178
+ * @throws PopSubError with code `user_not_found`, `bad_request` for the
179
+ * last enabled admin, or of kind `protocol` when the server answers
180
+ * with something other than `user_deleted`.
181
+ */
182
+ async deleteUser(username) {
183
+ const reply = await this.#send({ type: "delete_user", username });
184
+ if (reply.type !== "user_deleted") {
185
+ throw unexpected(reply, "user_deleted");
186
+ }
187
+ }
188
+ /**
189
+ * Lists every topic that has a log, sorted by name.
190
+ *
191
+ * @returns The topics.
192
+ * @throws PopSubError of kind `protocol` when the server answers with
193
+ * something other than `topics`.
194
+ */
195
+ async listTopics() {
196
+ const reply = await this.#send({ type: "list_topics" });
197
+ if (reply.type !== "topics") {
198
+ throw unexpected(reply, "topics");
199
+ }
200
+ return reply.topics.map(topicFromWire);
201
+ }
202
+ /**
203
+ * Reads a topic's bounds, record count and live subscriptions.
204
+ *
205
+ * @param topic - The topic.
206
+ * @returns The topic.
207
+ * @throws PopSubError with code `topic_not_found` when nothing was ever
208
+ * published to it.
209
+ */
210
+ getTopic(topic) {
211
+ return this.#topic({ type: "get_topic", topic });
212
+ }
213
+ /**
214
+ * Removes every record a topic holds. Its numbering carries on (the next
215
+ * publish gets `lastSeq + 1`), live subscriptions stay, and a subscriber
216
+ * that hadn't caught up gets `truncated`.
217
+ *
218
+ * @param topic - The topic.
219
+ * @returns The topic after the purge.
220
+ * @throws PopSubError with code `topic_not_found` when nothing was ever
221
+ * published to it.
222
+ */
223
+ purgeTopic(topic) {
224
+ return this.#topic({ type: "purge_topic", topic });
225
+ }
226
+ /**
227
+ * Sends a request answered by a `topic_info` frame.
228
+ *
229
+ * @param request - The request.
230
+ * @returns The topic in the reply.
231
+ * @throws PopSubError of kind `protocol` when the server answers with
232
+ * something other than `topic_info`.
233
+ */
234
+ async #topic(request) {
235
+ const reply = await this.#send(request);
236
+ if (reply.type !== "topic_info") {
237
+ throw unexpected(reply, "topic_info");
238
+ }
239
+ return topicFromWire(reply.topic);
240
+ }
241
+ /**
242
+ * Sends a request answered by a `user` frame.
243
+ *
244
+ * @param request - The request.
245
+ * @returns The account in the reply.
246
+ * @throws PopSubError of kind `protocol` when the server answers with
247
+ * something other than `user`.
248
+ */
249
+ async #user(request) {
250
+ const reply = await this.#send(request);
251
+ if (reply.type !== "user") {
252
+ throw unexpected(reply, "user");
253
+ }
254
+ return fromWire(reply.user);
255
+ }
256
+ }
257
+ //# sourceMappingURL=admin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin.js","sourceRoot":"","sources":["../src/admin.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,WAAW,E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,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"]}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Reconnect delays: a ceiling that doubles from `initialMs` up to `maxMs`,
3
+ * and a wait drawn at random between zero and that ceiling, so many clients
4
+ * reconnecting after a server restart don't all arrive at once.
5
+ *
6
+ * @module
7
+ */
8
+ /** The part of a reconnect policy that sets the delays. */
9
+ export interface BackoffPolicy {
10
+ /** The ceiling before the first retry is `initialMs` doubled once. */
11
+ initialMs: number;
12
+ /** The highest ceiling. */
13
+ maxMs: number;
14
+ }
15
+ /**
16
+ * The longest wait before an attempt, before jitter.
17
+ *
18
+ * @param policy - The delays.
19
+ * @param attempt - How many attempts in a row have failed, from 0.
20
+ * @returns `initialMs` doubled `attempt` times (at most 30 doublings),
21
+ * capped at `maxMs`.
22
+ */
23
+ export declare function backoffCeiling(policy: BackoffPolicy, attempt: number): number;
24
+ /**
25
+ * The wait before an attempt: a random time between zero and the ceiling.
26
+ *
27
+ * @param policy - The delays.
28
+ * @param attempt - How many attempts in a row have failed, from 0.
29
+ * @param random - A source of numbers in `[0, 1)`; `Math.random` by default.
30
+ * @returns The wait in milliseconds.
31
+ */
32
+ export declare function jitteredDelay(policy: BackoffPolicy, attempt: number, random?: () => number): number;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Reconnect delays: a ceiling that doubles from `initialMs` up to `maxMs`,
3
+ * and a wait drawn at random between zero and that ceiling, so many clients
4
+ * reconnecting after a server restart don't all arrive at once.
5
+ *
6
+ * @module
7
+ */
8
+ /**
9
+ * The longest wait before an attempt, before jitter.
10
+ *
11
+ * @param policy - The delays.
12
+ * @param attempt - How many attempts in a row have failed, from 0.
13
+ * @returns `initialMs` doubled `attempt` times (at most 30 doublings),
14
+ * capped at `maxMs`.
15
+ */
16
+ export function backoffCeiling(policy, attempt) {
17
+ const doublings = Math.min(Math.max(0, Math.floor(attempt)), 30);
18
+ return Math.min(policy.initialMs * 2 ** doublings, policy.maxMs);
19
+ }
20
+ /**
21
+ * The wait before an attempt: a random time between zero and the ceiling.
22
+ *
23
+ * @param policy - The delays.
24
+ * @param attempt - How many attempts in a row have failed, from 0.
25
+ * @param random - A source of numbers in `[0, 1)`; `Math.random` by default.
26
+ * @returns The wait in milliseconds.
27
+ */
28
+ export function jitteredDelay(policy, attempt, random = Math.random) {
29
+ return backoffCeiling(policy, attempt) * random();
30
+ }
31
+ //# sourceMappingURL=backoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backoff.js","sourceRoot":"","sources":["../src/backoff.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAUH;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,MAAqB,EAAE,OAAe;IACnE,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IACjE,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,SAAS,GAAG,CAAC,IAAI,SAAS,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;AACnE,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAC3B,MAAqB,EACrB,OAAe,EACf,SAAuB,IAAI,CAAC,MAAM;IAElC,OAAO,cAAc,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,EAAE,CAAC;AACpD,CAAC","sourcesContent":["/**\n * Reconnect delays: a ceiling that doubles from `initialMs` up to `maxMs`,\n * and a wait drawn at random between zero and that ceiling, so many clients\n * reconnecting after a server restart don't all arrive at once.\n *\n * @module\n */\n\n/** The part of a reconnect policy that sets the delays. */\nexport interface BackoffPolicy {\n /** The ceiling before the first retry is `initialMs` doubled once. */\n initialMs: number;\n /** The highest ceiling. */\n maxMs: number;\n}\n\n/**\n * The longest wait before an attempt, before jitter.\n *\n * @param policy - The delays.\n * @param attempt - How many attempts in a row have failed, from 0.\n * @returns `initialMs` doubled `attempt` times (at most 30 doublings),\n * capped at `maxMs`.\n */\nexport function backoffCeiling(policy: BackoffPolicy, attempt: number): number {\n const doublings = Math.min(Math.max(0, Math.floor(attempt)), 30);\n return Math.min(policy.initialMs * 2 ** doublings, policy.maxMs);\n}\n\n/**\n * The wait before an attempt: a random time between zero and the ceiling.\n *\n * @param policy - The delays.\n * @param attempt - How many attempts in a row have failed, from 0.\n * @param random - A source of numbers in `[0, 1)`; `Math.random` by default.\n * @returns The wait in milliseconds.\n */\nexport function jitteredDelay(\n policy: BackoffPolicy,\n attempt: number,\n random: () => number = Math.random,\n): number {\n return backoffCeiling(policy, attempt) * random();\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Standard padded base64 (RFC 4648 section 4), which is how a payload
3
+ * published as bytes travels. Written out here because `atob` accepts
4
+ * input the server would refuse (whitespace, missing padding) and
5
+ * `Buffer` doesn't exist in browsers.
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Encodes bytes as standard padded base64.
11
+ *
12
+ * @param bytes - The bytes.
13
+ * @returns The base64 text, a multiple of four characters long.
14
+ */
15
+ export declare function encodeBase64(bytes: Uint8Array): string;
16
+ /**
17
+ * Decodes standard padded base64, accepting only what an encoder writes:
18
+ * a length that is a multiple of four, characters from the alphabet,
19
+ * padding only at the end, and zero in the bits the padding leaves unused.
20
+ *
21
+ * @param text - The base64 text.
22
+ * @returns The bytes, or `null` when the text isn't valid base64.
23
+ */
24
+ export declare function decodeBase64(text: string): Uint8Array | null;
package/dist/base64.js ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Standard padded base64 (RFC 4648 section 4), which is how a payload
3
+ * published as bytes travels. Written out here because `atob` accepts
4
+ * input the server would refuse (whitespace, missing padding) and
5
+ * `Buffer` doesn't exist in browsers.
6
+ *
7
+ * @module
8
+ */
9
+ /** The base64 alphabet, indexed by six-bit value. */
10
+ const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
11
+ /** The six-bit value of each alphabet character, by character code; -1 elsewhere. */
12
+ const VALUES = buildValues();
13
+ /**
14
+ * Builds the table that maps a character code to its six-bit value.
15
+ *
16
+ * @returns The table, with -1 for every code outside the alphabet.
17
+ */
18
+ function buildValues() {
19
+ const values = new Int8Array(128).fill(-1);
20
+ for (let i = 0; i < ALPHABET.length; i += 1) {
21
+ values[ALPHABET.charCodeAt(i)] = i;
22
+ }
23
+ return values;
24
+ }
25
+ /**
26
+ * Reads the six-bit value of one character of a base64 string.
27
+ *
28
+ * @param text - The base64 string.
29
+ * @param index - The character's position.
30
+ * @returns The value, or -1 when the character isn't in the alphabet.
31
+ */
32
+ function valueAt(text, index) {
33
+ const code = text.charCodeAt(index);
34
+ return code < VALUES.length ? (VALUES[code] ?? -1) : -1;
35
+ }
36
+ /**
37
+ * Encodes bytes as standard padded base64.
38
+ *
39
+ * @param bytes - The bytes.
40
+ * @returns The base64 text, a multiple of four characters long.
41
+ */
42
+ export function encodeBase64(bytes) {
43
+ const parts = [];
44
+ let chunk = "";
45
+ for (let i = 0; i < bytes.length; i += 3) {
46
+ const first = bytes[i] ?? 0;
47
+ const second = bytes[i + 1] ?? 0;
48
+ const third = bytes[i + 2] ?? 0;
49
+ const left = bytes.length - i;
50
+ chunk += ALPHABET.charAt(first >> 2);
51
+ chunk += ALPHABET.charAt(((first & 0x03) << 4) | (second >> 4));
52
+ chunk += left > 1 ? ALPHABET.charAt(((second & 0x0f) << 2) | (third >> 6)) : "=";
53
+ chunk += left > 2 ? ALPHABET.charAt(third & 0x3f) : "=";
54
+ if (chunk.length >= 8192) {
55
+ parts.push(chunk);
56
+ chunk = "";
57
+ }
58
+ }
59
+ parts.push(chunk);
60
+ return parts.join("");
61
+ }
62
+ /**
63
+ * Decodes standard padded base64, accepting only what an encoder writes:
64
+ * a length that is a multiple of four, characters from the alphabet,
65
+ * padding only at the end, and zero in the bits the padding leaves unused.
66
+ *
67
+ * @param text - The base64 text.
68
+ * @returns The bytes, or `null` when the text isn't valid base64.
69
+ */
70
+ export function decodeBase64(text) {
71
+ if (text.length % 4 !== 0) {
72
+ return null;
73
+ }
74
+ let padding = 0;
75
+ if (text.endsWith("==")) {
76
+ padding = 2;
77
+ }
78
+ else if (text.endsWith("=")) {
79
+ padding = 1;
80
+ }
81
+ const bytes = new Uint8Array((text.length / 4) * 3 - padding);
82
+ let written = 0;
83
+ for (let i = 0; i < text.length; i += 4) {
84
+ const last = i + 4 === text.length;
85
+ const a = valueAt(text, i);
86
+ const b = valueAt(text, i + 1);
87
+ const c = last && padding === 2 ? 0 : valueAt(text, i + 2);
88
+ const d = last && padding >= 1 ? 0 : valueAt(text, i + 3);
89
+ if (a < 0 || b < 0 || c < 0 || d < 0) {
90
+ return null;
91
+ }
92
+ if (last && ((padding === 2 && (b & 0x0f) !== 0) || (padding === 1 && (c & 0x03) !== 0))) {
93
+ return null;
94
+ }
95
+ const group = (a << 18) | (b << 12) | (c << 6) | d;
96
+ const count = last ? 3 - padding : 3;
97
+ for (let k = 0; k < count; k += 1) {
98
+ bytes[written] = (group >> (16 - 8 * k)) & 0xff;
99
+ written += 1;
100
+ }
101
+ }
102
+ return bytes;
103
+ }
104
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.js","sourceRoot":"","sources":["../src/base64.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,qDAAqD;AACrD,MAAM,QAAQ,GAAG,kEAAkE,CAAC;AAEpF,qFAAqF;AACrF,MAAM,MAAM,GAAc,WAAW,EAAE,CAAC;AAExC;;;;GAIG;AACH,SAAS,WAAW;IAClB,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5C,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACrC,CAAC;IACD,OAAO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OAAO,IAAI,CAAC,CAAC;QACf,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["/**\n * Standard padded base64 (RFC 4648 section 4), which is how a payload\n * published as bytes travels. Written out here because `atob` accepts\n * input the server would refuse (whitespace, missing padding) and\n * `Buffer` doesn't exist in browsers.\n *\n * @module\n */\n\n/** The base64 alphabet, indexed by six-bit value. */\nconst ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/** The six-bit value of each alphabet character, by character code; -1 elsewhere. */\nconst VALUES: Int8Array = buildValues();\n\n/**\n * Builds the table that maps a character code to its six-bit value.\n *\n * @returns The table, with -1 for every code outside the alphabet.\n */\nfunction buildValues(): Int8Array {\n const values = new Int8Array(128).fill(-1);\n for (let i = 0; i < ALPHABET.length; i += 1) {\n values[ALPHABET.charCodeAt(i)] = i;\n }\n return values;\n}\n\n/**\n * Reads the six-bit value of one character of a base64 string.\n *\n * @param text - The base64 string.\n * @param index - The character's position.\n * @returns The value, or -1 when the character isn't in the alphabet.\n */\nfunction valueAt(text: string, index: number): number {\n const code = text.charCodeAt(index);\n return code < VALUES.length ? (VALUES[code] ?? -1) : -1;\n}\n\n/**\n * Encodes bytes as standard padded base64.\n *\n * @param bytes - The bytes.\n * @returns The base64 text, a multiple of four characters long.\n */\nexport function encodeBase64(bytes: Uint8Array): string {\n const parts: string[] = [];\n let chunk = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const first = bytes[i] ?? 0;\n const second = bytes[i + 1] ?? 0;\n const third = bytes[i + 2] ?? 0;\n const left = bytes.length - i;\n chunk += ALPHABET.charAt(first >> 2);\n chunk += ALPHABET.charAt(((first & 0x03) << 4) | (second >> 4));\n chunk += left > 1 ? ALPHABET.charAt(((second & 0x0f) << 2) | (third >> 6)) : \"=\";\n chunk += left > 2 ? ALPHABET.charAt(third & 0x3f) : \"=\";\n if (chunk.length >= 8192) {\n parts.push(chunk);\n chunk = \"\";\n }\n }\n parts.push(chunk);\n return parts.join(\"\");\n}\n\n/**\n * Decodes standard padded base64, accepting only what an encoder writes:\n * a length that is a multiple of four, characters from the alphabet,\n * padding only at the end, and zero in the bits the padding leaves unused.\n *\n * @param text - The base64 text.\n * @returns The bytes, or `null` when the text isn't valid base64.\n */\nexport function decodeBase64(text: string): Uint8Array | null {\n if (text.length % 4 !== 0) {\n return null;\n }\n let padding = 0;\n if (text.endsWith(\"==\")) {\n padding = 2;\n } else if (text.endsWith(\"=\")) {\n padding = 1;\n }\n const bytes = new Uint8Array((text.length / 4) * 3 - padding);\n let written = 0;\n for (let i = 0; i < text.length; i += 4) {\n const last = i + 4 === text.length;\n const a = valueAt(text, i);\n const b = valueAt(text, i + 1);\n const c = last && padding === 2 ? 0 : valueAt(text, i + 2);\n const d = last && padding >= 1 ? 0 : valueAt(text, i + 3);\n if (a < 0 || b < 0 || c < 0 || d < 0) {\n return null;\n }\n if (last && ((padding === 2 && (b & 0x0f) !== 0) || (padding === 1 && (c & 0x03) !== 0))) {\n return null;\n }\n const group = (a << 18) | (b << 12) | (c << 6) | d;\n const count = last ? 3 - padding : 3;\n for (let k = 0; k < count; k += 1) {\n bytes[written] = (group >> (16 - 8 * k)) & 0xff;\n written += 1;\n }\n }\n return bytes;\n}\n"]}