popsub 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * One connection attempt up to authentication: opening the WebSocket, then
3
+ * request and reply exchanges (`login`, `auth`) before the connection is
4
+ * handed to the engine. Frames that arrive after the last reply and before
5
+ * the hand-over are kept, so none is lost between the two.
6
+ *
7
+ * @module
8
+ */
9
+ import { PopSubError } from "./errors.js";
10
+ import { type ClientMessage, type ServerMessage } from "./protocol.js";
11
+ /** Why a connection attempt failed, and whether another attempt could help. */
12
+ export declare class ConnectFailure extends Error {
13
+ /** The error to report. */
14
+ readonly error: PopSubError;
15
+ /** Whether retrying could help. */
16
+ readonly retry: boolean;
17
+ /**
18
+ * Builds a failure.
19
+ *
20
+ * @param error - The error to report, which also becomes the cause.
21
+ * @param retry - Whether retrying could help.
22
+ */
23
+ constructor(error: PopSubError, retry: boolean);
24
+ }
25
+ /** Thrown into a waiting attempt when the application closes the client. */
26
+ export declare class Aborted extends Error {
27
+ /** Builds the marker error. */
28
+ constructor();
29
+ }
30
+ /** Where a served connection's frames and close go once it is handed over. */
31
+ export interface ConnectionHandlers {
32
+ /**
33
+ * Called with each text frame.
34
+ *
35
+ * @param text - The frame's text.
36
+ */
37
+ text(text: string): void;
38
+ /**
39
+ * Called once when the connection closes.
40
+ *
41
+ * @param code - The close event's code.
42
+ */
43
+ closed(code: number): void;
44
+ }
45
+ /** A WebSocket during its connection attempt. */
46
+ export declare class Handshake {
47
+ #private;
48
+ /** The socket. */
49
+ readonly socket: WebSocket;
50
+ /**
51
+ * Opens a WebSocket.
52
+ *
53
+ * @param url - The server's URL.
54
+ * @param timeoutMs - How long each step may take.
55
+ * @throws PopSubError of kind `config` when there is no global
56
+ * `WebSocket` or the URL is rejected.
57
+ */
58
+ constructor(url: string, timeoutMs: number);
59
+ /**
60
+ * Waits for the socket to open.
61
+ *
62
+ * @throws ConnectFailure when it closes first or takes too long.
63
+ * @throws Aborted when the application closed the client.
64
+ */
65
+ opened(): Promise<void>;
66
+ /**
67
+ * Sends a request and waits for the reply with its id. Other frames are ignored.
68
+ *
69
+ * @param id - The request id.
70
+ * @param message - The request.
71
+ * @returns The reply.
72
+ * @throws ConnectFailure when the connection closes first or no reply
73
+ * arrives within the timeout.
74
+ * @throws Aborted when the application closed the client.
75
+ */
76
+ exchange(id: number, message: ClientMessage): Promise<ServerMessage>;
77
+ /**
78
+ * Fails the current wait because the application closed the client, and
79
+ * closes the socket.
80
+ */
81
+ abort(): void;
82
+ /** Closes the socket and stops listening to it. */
83
+ close(): void;
84
+ /**
85
+ * Hands the connection to the engine.
86
+ *
87
+ * @param handlers - Where its frames and close go from now on.
88
+ * @returns The frames that arrived after the last reply, in order.
89
+ */
90
+ handOver(handlers: ConnectionHandlers): string[];
91
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * One connection attempt up to authentication: opening the WebSocket, then
3
+ * request and reply exchanges (`login`, `auth`) before the connection is
4
+ * handed to the engine. Frames that arrive after the last reply and before
5
+ * the hand-over are kept, so none is lost between the two.
6
+ *
7
+ * @module
8
+ */
9
+ import { PopSubError } from "./errors.js";
10
+ import { closeCode, encodeFrame, parseServerFrame, shouldReconnect, } from "./protocol.js";
11
+ /**
12
+ * The close code reported when the socket fails without a close frame.
13
+ * Some runtimes (Node 22's WebSocket, for one) fire only `error`, not
14
+ * `close`, when a connection attempt is refused, so `error` is handled as a
15
+ * close with this code; whichever of the two arrives first detaches both.
16
+ */
17
+ const ABNORMAL_CLOSURE = 1006;
18
+ /** Why a connection attempt failed, and whether another attempt could help. */
19
+ export class ConnectFailure extends Error {
20
+ /** The error to report. */
21
+ error;
22
+ /** Whether retrying could help. */
23
+ retry;
24
+ /**
25
+ * Builds a failure.
26
+ *
27
+ * @param error - The error to report, which also becomes the cause.
28
+ * @param retry - Whether retrying could help.
29
+ */
30
+ constructor(error, retry) {
31
+ super(error.message, { cause: error });
32
+ this.name = "ConnectFailure";
33
+ this.error = error;
34
+ this.retry = retry;
35
+ }
36
+ }
37
+ /** Thrown into a waiting attempt when the application closes the client. */
38
+ export class Aborted extends Error {
39
+ /** Builds the marker error. */
40
+ constructor() {
41
+ super("aborted");
42
+ this.name = "Aborted";
43
+ }
44
+ }
45
+ /** A WebSocket during its connection attempt. */
46
+ export class Handshake {
47
+ /** The socket. */
48
+ socket;
49
+ /** How long each step may take, in milliseconds. */
50
+ #timeoutMs;
51
+ /** Whether the socket has opened. */
52
+ #opened = false;
53
+ /** Why the attempt can no longer succeed, once it can't. */
54
+ #failure = null;
55
+ /** The current wait. */
56
+ #waiter = null;
57
+ /** Whether frames are being kept for the hand-over. */
58
+ #capturing = false;
59
+ /** Frames kept for the hand-over. */
60
+ #early = [];
61
+ /** Where frames go after the hand-over. */
62
+ #handlers = null;
63
+ /**
64
+ * Opens a WebSocket.
65
+ *
66
+ * @param url - The server's URL.
67
+ * @param timeoutMs - How long each step may take.
68
+ * @throws PopSubError of kind `config` when there is no global
69
+ * `WebSocket` or the URL is rejected.
70
+ */
71
+ constructor(url, timeoutMs) {
72
+ if (typeof globalThis.WebSocket !== "function") {
73
+ throw new PopSubError("config", "this runtime has no global WebSocket; Node.js 22 or later is required");
74
+ }
75
+ try {
76
+ this.socket = new WebSocket(url);
77
+ }
78
+ catch (error) {
79
+ const reason = error instanceof Error ? error.message : String(error);
80
+ throw new PopSubError("config", `invalid url: ${reason}`, { cause: error });
81
+ }
82
+ this.#timeoutMs = timeoutMs;
83
+ this.socket.onopen = () => {
84
+ this.#onOpen();
85
+ };
86
+ this.socket.onmessage = (event) => {
87
+ this.#onMessage(event.data);
88
+ };
89
+ this.socket.onclose = (event) => {
90
+ this.#onClose(event.code);
91
+ };
92
+ this.socket.onerror = () => {
93
+ this.#onClose(ABNORMAL_CLOSURE);
94
+ };
95
+ }
96
+ /**
97
+ * Waits for the socket to open.
98
+ *
99
+ * @throws ConnectFailure when it closes first or takes too long.
100
+ * @throws Aborted when the application closed the client.
101
+ */
102
+ async opened() {
103
+ if (!this.#opened) {
104
+ await this.#wait(null);
105
+ }
106
+ }
107
+ /**
108
+ * Sends a request and waits for the reply with its id. Other frames are ignored.
109
+ *
110
+ * @param id - The request id.
111
+ * @param message - The request.
112
+ * @returns The reply.
113
+ * @throws ConnectFailure when the connection closes first or no reply
114
+ * arrives within the timeout.
115
+ * @throws Aborted when the application closed the client.
116
+ */
117
+ async exchange(id, message) {
118
+ this.#capturing = false;
119
+ this.#early = [];
120
+ if (this.#failure === null) {
121
+ this.socket.send(encodeFrame(message, id));
122
+ }
123
+ const reply = await this.#wait(id);
124
+ if (reply === null) {
125
+ throw new ConnectFailure(new PopSubError("protocol", "no reply to the request"), true);
126
+ }
127
+ return reply;
128
+ }
129
+ /**
130
+ * Fails the current wait because the application closed the client, and
131
+ * closes the socket.
132
+ */
133
+ abort() {
134
+ this.#fail(new Aborted());
135
+ this.close();
136
+ }
137
+ /** Closes the socket and stops listening to it. */
138
+ close() {
139
+ this.#detach();
140
+ try {
141
+ this.socket.close(1000);
142
+ }
143
+ catch {
144
+ return;
145
+ }
146
+ }
147
+ /**
148
+ * Hands the connection to the engine.
149
+ *
150
+ * @param handlers - Where its frames and close go from now on.
151
+ * @returns The frames that arrived after the last reply, in order.
152
+ */
153
+ handOver(handlers) {
154
+ this.#handlers = handlers;
155
+ const early = this.#early;
156
+ this.#early = [];
157
+ this.#capturing = false;
158
+ return early;
159
+ }
160
+ /**
161
+ * Starts a wait, failing at once if the attempt has already failed.
162
+ *
163
+ * @param id - The reply's request id, or `null` to wait for the socket to open.
164
+ * @returns The reply, or `null` for the open.
165
+ */
166
+ #wait(id) {
167
+ return new Promise((resolve, reject) => {
168
+ if (this.#failure !== null) {
169
+ reject(this.#failure);
170
+ return;
171
+ }
172
+ const timer = setTimeout(() => {
173
+ this.#fail(new ConnectFailure(PopSubError.timeout(), true));
174
+ }, this.#timeoutMs);
175
+ this.#waiter = {
176
+ id,
177
+ resolve: (reply) => {
178
+ clearTimeout(timer);
179
+ this.#waiter = null;
180
+ resolve(reply);
181
+ },
182
+ reject: (reason) => {
183
+ clearTimeout(timer);
184
+ this.#waiter = null;
185
+ reject(reason);
186
+ },
187
+ };
188
+ });
189
+ }
190
+ /**
191
+ * Records why the attempt failed and fails the current wait.
192
+ *
193
+ * @param reason - The failure.
194
+ */
195
+ #fail(reason) {
196
+ if (this.#failure === null) {
197
+ this.#failure = reason;
198
+ }
199
+ this.#waiter?.reject(this.#failure);
200
+ }
201
+ /** Settles a wait for the socket to open. */
202
+ #onOpen() {
203
+ this.#opened = true;
204
+ if (this.#waiter !== null && this.#waiter.id === null) {
205
+ this.#waiter.resolve(null);
206
+ }
207
+ }
208
+ /**
209
+ * Routes a frame: to the engine after the hand-over, to the kept frames
210
+ * after a reply, or to the waiting exchange if it is its reply.
211
+ *
212
+ * @param data - The frame's data; binary frames are ignored.
213
+ */
214
+ #onMessage(data) {
215
+ if (typeof data !== "string") {
216
+ return;
217
+ }
218
+ if (this.#handlers !== null) {
219
+ this.#handlers.text(data);
220
+ return;
221
+ }
222
+ if (this.#capturing) {
223
+ this.#early.push(data);
224
+ return;
225
+ }
226
+ const waiter = this.#waiter;
227
+ if (waiter?.id == null) {
228
+ return;
229
+ }
230
+ const frame = parseServerFrame(data);
231
+ if (frame !== null && frame.id === waiter.id) {
232
+ this.#capturing = true;
233
+ waiter.resolve(frame);
234
+ }
235
+ }
236
+ /**
237
+ * Handles the socket closing: tells the engine after the hand-over,
238
+ * otherwise fails the attempt. Before the socket opened the server
239
+ * couldn't be reached; after, the close code decides whether to retry.
240
+ *
241
+ * @param raw - The close event's code.
242
+ */
243
+ #onClose(raw) {
244
+ if (this.#handlers !== null) {
245
+ const handlers = this.#handlers;
246
+ this.#detach();
247
+ handlers.closed(raw);
248
+ return;
249
+ }
250
+ if (!this.#opened) {
251
+ this.#fail(new ConnectFailure(new PopSubError("connect", `can't connect to the server (close code ${String(raw)})`), true));
252
+ return;
253
+ }
254
+ const code = closeCode(raw);
255
+ this.#fail(new ConnectFailure(PopSubError.closed(code), code === null || shouldReconnect(code)));
256
+ }
257
+ /** Stops listening to the socket. */
258
+ #detach() {
259
+ this.#handlers = null;
260
+ this.socket.onopen = null;
261
+ this.socket.onmessage = null;
262
+ this.socket.onclose = null;
263
+ this.socket.onerror = null;
264
+ }
265
+ }
266
+ //# sourceMappingURL=handshake.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handshake.js","sourceRoot":"","sources":["../src/handshake.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACL,SAAS,EACT,WAAW,EACX,gBAAgB,EAChB,eAAe,GAGhB,MAAM,eAAe,CAAC;AAEvB;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B,+EAA+E;AAC/E,MAAM,OAAO,cAAe,SAAQ,KAAK;IACvC,2BAA2B;IAClB,KAAK,CAAc;IAC5B,mCAAmC;IAC1B,KAAK,CAAU;IAExB;;;;;OAKG;IACH,YAAY,KAAkB,EAAE,KAAc;QAC5C,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvC,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;QAC7B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;CACF;AAED,4EAA4E;AAC5E,MAAM,OAAO,OAAQ,SAAQ,KAAK;IAChC,+BAA+B;IAC/B;QACE,KAAK,CAAC,SAAS,CAAC,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;IACxB,CAAC;CACF;AA4BD,iDAAiD;AACjD,MAAM,OAAO,SAAS;IACpB,kBAAkB;IACT,MAAM,CAAY;IAC3B,oDAAoD;IAC3C,UAAU,CAAS;IAC5B,qCAAqC;IACrC,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;YAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC;YAChC,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACrB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC,KAAK,CACR,IAAI,cAAc,CAChB,IAAI,WAAW,CAAC,SAAS,EAAE,2CAA2C,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EACrF,IAAI,CACL,CACF,CAAC;YACF,OAAO;QACT,CAAC;QACD,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC;QAC5B,IAAI,CAAC,KAAK,CAAC,IAAI,cAAc,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,KAAK,IAAI,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACnG,CAAC;IAED,qCAAqC;IACrC,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;QAC7B,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;QAC3B,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC;IAC7B,CAAC;CACF","sourcesContent":["/**\n * One connection attempt up to authentication: opening the WebSocket, then\n * request and reply exchanges (`login`, `auth`) before the connection is\n * handed to the engine. Frames that arrive after the last reply and before\n * the hand-over are kept, so none is lost between the two.\n *\n * @module\n */\n\nimport { PopSubError } from \"./errors.js\";\nimport {\n closeCode,\n encodeFrame,\n parseServerFrame,\n shouldReconnect,\n type ClientMessage,\n type ServerMessage,\n} from \"./protocol.js\";\n\n/**\n * The close code reported when the socket fails without a close frame.\n * Some runtimes (Node 22's WebSocket, for one) fire only `error`, not\n * `close`, when a connection attempt is refused, so `error` is handled as a\n * close with this code; whichever of the two arrives first detaches both.\n */\nconst ABNORMAL_CLOSURE = 1006;\n\n/** Why a connection attempt failed, and whether another attempt could help. */\nexport class ConnectFailure extends Error {\n /** The error to report. */\n readonly error: PopSubError;\n /** Whether retrying could help. */\n readonly retry: boolean;\n\n /**\n * Builds a failure.\n *\n * @param error - The error to report, which also becomes the cause.\n * @param retry - Whether retrying could help.\n */\n constructor(error: PopSubError, retry: boolean) {\n super(error.message, { cause: error });\n this.name = \"ConnectFailure\";\n this.error = error;\n this.retry = retry;\n }\n}\n\n/** Thrown into a waiting attempt when the application closes the client. */\nexport class Aborted extends Error {\n /** Builds the marker error. */\n constructor() {\n super(\"aborted\");\n this.name = \"Aborted\";\n }\n}\n\n/** Where a served connection's frames and close go once it is handed over. */\nexport interface ConnectionHandlers {\n /**\n * Called with each text frame.\n *\n * @param text - The frame's text.\n */\n text(text: string): void;\n /**\n * Called once when the connection closes.\n *\n * @param code - The close event's code.\n */\n closed(code: number): void;\n}\n\n/** A pending wait for the socket to open or for one reply. */\ninterface Waiter {\n /** The request id whose reply is awaited, or `null` while waiting to open. */\n id: number | null;\n /** Settles the wait with a reply. */\n resolve(reply: ServerMessage | null): void;\n /** Fails the wait. */\n reject(reason: ConnectFailure | Aborted): void;\n}\n\n/** A WebSocket during its connection attempt. */\nexport class Handshake {\n /** The socket. */\n readonly socket: WebSocket;\n /** How long each step may take, in milliseconds. */\n readonly #timeoutMs: number;\n /** Whether the socket has opened. */\n #opened = false;\n /** Why the attempt can no longer succeed, once it can't. */\n #failure: ConnectFailure | Aborted | null = null;\n /** The current wait. */\n #waiter: Waiter | null = null;\n /** Whether frames are being kept for the hand-over. */\n #capturing = false;\n /** Frames kept for the hand-over. */\n #early: string[] = [];\n /** Where frames go after the hand-over. */\n #handlers: ConnectionHandlers | null = null;\n\n /**\n * Opens a WebSocket.\n *\n * @param url - The server's URL.\n * @param timeoutMs - How long each step may take.\n * @throws PopSubError of kind `config` when there is no global\n * `WebSocket` or the URL is rejected.\n */\n constructor(url: string, timeoutMs: number) {\n if (typeof globalThis.WebSocket !== \"function\") {\n throw new PopSubError(\n \"config\",\n \"this runtime has no global WebSocket; Node.js 22 or later is required\",\n );\n }\n try {\n this.socket = new WebSocket(url);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new PopSubError(\"config\", `invalid url: ${reason}`, { cause: error });\n }\n this.#timeoutMs = timeoutMs;\n this.socket.onopen = () => {\n this.#onOpen();\n };\n this.socket.onmessage = (event: MessageEvent) => {\n this.#onMessage(event.data);\n };\n this.socket.onclose = (event: CloseEvent) => {\n this.#onClose(event.code);\n };\n this.socket.onerror = () => {\n this.#onClose(ABNORMAL_CLOSURE);\n };\n }\n\n /**\n * Waits for the socket to open.\n *\n * @throws ConnectFailure when it closes first or takes too long.\n * @throws Aborted when the application closed the client.\n */\n async opened(): Promise<void> {\n if (!this.#opened) {\n await this.#wait(null);\n }\n }\n\n /**\n * Sends a request and waits for the reply with its id. Other frames are ignored.\n *\n * @param id - The request id.\n * @param message - The request.\n * @returns The reply.\n * @throws ConnectFailure when the connection closes first or no reply\n * arrives within the timeout.\n * @throws Aborted when the application closed the client.\n */\n async exchange(id: number, message: ClientMessage): Promise<ServerMessage> {\n this.#capturing = false;\n this.#early = [];\n if (this.#failure === null) {\n this.socket.send(encodeFrame(message, id));\n }\n const reply = await this.#wait(id);\n if (reply === null) {\n throw new ConnectFailure(new PopSubError(\"protocol\", \"no reply to the request\"), true);\n }\n return reply;\n }\n\n /**\n * Fails the current wait because the application closed the client, and\n * closes the socket.\n */\n abort(): void {\n this.#fail(new Aborted());\n this.close();\n }\n\n /** Closes the socket and stops listening to it. */\n close(): void {\n this.#detach();\n try {\n this.socket.close(1000);\n } catch {\n return;\n }\n }\n\n /**\n * Hands the connection to the engine.\n *\n * @param handlers - Where its frames and close go from now on.\n * @returns The frames that arrived after the last reply, in order.\n */\n handOver(handlers: ConnectionHandlers): string[] {\n this.#handlers = handlers;\n const early = this.#early;\n this.#early = [];\n this.#capturing = false;\n return early;\n }\n\n /**\n * Starts a wait, failing at once if the attempt has already failed.\n *\n * @param id - The reply's request id, or `null` to wait for the socket to open.\n * @returns The reply, or `null` for the open.\n */\n #wait(id: number | null): Promise<ServerMessage | null> {\n return new Promise((resolve, reject) => {\n if (this.#failure !== null) {\n reject(this.#failure);\n return;\n }\n const timer = setTimeout(() => {\n this.#fail(new ConnectFailure(PopSubError.timeout(), true));\n }, this.#timeoutMs);\n this.#waiter = {\n id,\n resolve: (reply) => {\n clearTimeout(timer);\n this.#waiter = null;\n resolve(reply);\n },\n reject: (reason) => {\n clearTimeout(timer);\n this.#waiter = null;\n reject(reason);\n },\n };\n });\n }\n\n /**\n * Records why the attempt failed and fails the current wait.\n *\n * @param reason - The failure.\n */\n #fail(reason: ConnectFailure | Aborted): void {\n if (this.#failure === null) {\n this.#failure = reason;\n }\n this.#waiter?.reject(this.#failure);\n }\n\n /** Settles a wait for the socket to open. */\n #onOpen(): void {\n this.#opened = true;\n if (this.#waiter !== null && this.#waiter.id === null) {\n this.#waiter.resolve(null);\n }\n }\n\n /**\n * Routes a frame: to the engine after the hand-over, to the kept frames\n * after a reply, or to the waiting exchange if it is its reply.\n *\n * @param data - The frame's data; binary frames are ignored.\n */\n #onMessage(data: unknown): void {\n if (typeof data !== \"string\") {\n return;\n }\n if (this.#handlers !== null) {\n this.#handlers.text(data);\n return;\n }\n if (this.#capturing) {\n this.#early.push(data);\n return;\n }\n const waiter = this.#waiter;\n if (waiter?.id == null) {\n return;\n }\n const frame = parseServerFrame(data);\n if (frame !== null && frame.id === waiter.id) {\n this.#capturing = true;\n waiter.resolve(frame);\n }\n }\n\n /**\n * Handles the socket closing: tells the engine after the hand-over,\n * otherwise fails the attempt. Before the socket opened the server\n * couldn't be reached; after, the close code decides whether to retry.\n *\n * @param raw - The close event's code.\n */\n #onClose(raw: number): void {\n if (this.#handlers !== null) {\n const handlers = this.#handlers;\n this.#detach();\n handlers.closed(raw);\n return;\n }\n if (!this.#opened) {\n this.#fail(\n new ConnectFailure(\n new PopSubError(\"connect\", `can't connect to the server (close code ${String(raw)})`),\n true,\n ),\n );\n return;\n }\n const code = closeCode(raw);\n this.#fail(new ConnectFailure(PopSubError.closed(code), code === null || shouldReconnect(code)));\n }\n\n /** Stops listening to the socket. */\n #detach(): void {\n this.#handlers = null;\n this.socket.onopen = null;\n this.socket.onmessage = null;\n this.socket.onclose = null;\n this.socket.onerror = null;\n }\n}\n"]}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The PopSub client for browsers and Node.js 22 or later.
3
+ *
4
+ * ```ts
5
+ * import { Client } from "popsub";
6
+ *
7
+ * const client = await Client.connect({
8
+ * url: "ws://127.0.0.1:8080",
9
+ * credentials: { username: "alice", password: "secret-password" },
10
+ * sessionId: "alice-laptop",
11
+ * });
12
+ * const orders = await client.subscribe("orders", "resume");
13
+ * const stored = await client.publishConfirmed("orders", "order 42 shipped");
14
+ * client.publishBytes("orders", new Uint8Array([0x00, 0xff]));
15
+ * for await (const message of orders) {
16
+ * console.log(message.topic, message.seq, message.payload);
17
+ * }
18
+ * ```
19
+ *
20
+ * A payload is a string. `publishBytes` and `publishBytesConfirmed` send a
21
+ * body that isn't text as base64, and `Message.bytes` returns the bytes of
22
+ * any message.
23
+ *
24
+ * The protocol is documented in the repository's `docs/DESIGN.md` section 4.
25
+ *
26
+ * @module
27
+ */
28
+ export { Admin, type TopicInfo, type User } from "./admin.js";
29
+ export { Client, type StartFrom } from "./client.js";
30
+ export type { AckMode, ClientConfig, Credentials, PasswordCredentials, ReconnectPolicy, TokenCredentials, } from "./config.js";
31
+ export type { Published } from "./engine.js";
32
+ export { PopSubError, type ErrorKind } from "./errors.js";
33
+ export type { AuthExpiringEvent, AuthRefreshedEvent, ClientEvent, ClientEventListener, ConnectedEvent, DisconnectedEvent, ServerErrorEvent, StalledEvent, TruncatedEvent, UnsubscribedEvent, } from "./events.js";
34
+ export { CloseCode, ERROR_CODES, PROTOCOL_VERSION, type Access, type Encoding, type ErrorCode, type RoleKind, type RoleSpec, type TopicGrant, } from "./protocol.js";
35
+ export { Message, Subscription } from "./subscription.js";
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The PopSub client for browsers and Node.js 22 or later.
3
+ *
4
+ * ```ts
5
+ * import { Client } from "popsub";
6
+ *
7
+ * const client = await Client.connect({
8
+ * url: "ws://127.0.0.1:8080",
9
+ * credentials: { username: "alice", password: "secret-password" },
10
+ * sessionId: "alice-laptop",
11
+ * });
12
+ * const orders = await client.subscribe("orders", "resume");
13
+ * const stored = await client.publishConfirmed("orders", "order 42 shipped");
14
+ * client.publishBytes("orders", new Uint8Array([0x00, 0xff]));
15
+ * for await (const message of orders) {
16
+ * console.log(message.topic, message.seq, message.payload);
17
+ * }
18
+ * ```
19
+ *
20
+ * A payload is a string. `publishBytes` and `publishBytesConfirmed` send a
21
+ * body that isn't text as base64, and `Message.bytes` returns the bytes of
22
+ * any message.
23
+ *
24
+ * The protocol is documented in the repository's `docs/DESIGN.md` section 4.
25
+ *
26
+ * @module
27
+ */
28
+ export { Admin } from "./admin.js";
29
+ export { Client } from "./client.js";
30
+ export { PopSubError } from "./errors.js";
31
+ export { CloseCode, ERROR_CODES, PROTOCOL_VERSION, } from "./protocol.js";
32
+ export { Message, Subscription } from "./subscription.js";
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EAAE,KAAK,EAA6B,MAAM,YAAY,CAAC;AAC9D,OAAO,EAAE,MAAM,EAAkB,MAAM,aAAa,CAAC;AAUrD,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 TopicInfo, type User } from \"./admin.js\";\nexport { Client, type StartFrom } from \"./client.js\";\nexport type {\n AckMode,\n ClientConfig,\n Credentials,\n PasswordCredentials,\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"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Topic patterns for wildcard subscriptions: a topic name in which a whole
3
+ * level may be `+` (any one level) and the last level may be `#` (that
4
+ * level and everything below it). Mirrors `popsub_protocol::topics`.
5
+ *
6
+ * @module
7
+ */
8
+ /**
9
+ * Whether a string has a wildcard, so it is a pattern and not a plain topic name.
10
+ *
11
+ * @param topic - The string.
12
+ * @returns True when it contains `+` or `#`.
13
+ */
14
+ export declare function isPattern(topic: string): boolean;
15
+ /**
16
+ * Whether a topic matches a pattern. `+` stands for exactly one level and
17
+ * `#`, which ends a pattern, for the rest of the topic, including nothing
18
+ * (`orders/#` matches `orders`).
19
+ *
20
+ * @param pattern - The pattern.
21
+ * @param topic - The topic name.
22
+ * @returns True when the topic matches.
23
+ */
24
+ export declare function matchesPattern(pattern: string, topic: string): boolean;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Topic patterns for wildcard subscriptions: a topic name in which a whole
3
+ * level may be `+` (any one level) and the last level may be `#` (that
4
+ * level and everything below it). Mirrors `popsub_protocol::topics`.
5
+ *
6
+ * @module
7
+ */
8
+ /**
9
+ * Whether a string has a wildcard, so it is a pattern and not a plain topic name.
10
+ *
11
+ * @param topic - The string.
12
+ * @returns True when it contains `+` or `#`.
13
+ */
14
+ export function isPattern(topic) {
15
+ return topic.includes("+") || topic.includes("#");
16
+ }
17
+ /**
18
+ * Whether a topic matches a pattern. `+` stands for exactly one level and
19
+ * `#`, which ends a pattern, for the rest of the topic, including nothing
20
+ * (`orders/#` matches `orders`).
21
+ *
22
+ * @param pattern - The pattern.
23
+ * @param topic - The topic name.
24
+ * @returns True when the topic matches.
25
+ */
26
+ export function matchesPattern(pattern, topic) {
27
+ if (pattern === topic) {
28
+ return true;
29
+ }
30
+ const levels = pattern.split("/");
31
+ const parts = topic.split("/");
32
+ for (const [index, level] of levels.entries()) {
33
+ if (level === "#") {
34
+ return true;
35
+ }
36
+ const part = parts[index];
37
+ if (part === undefined || (level !== "+" && level !== part)) {
38
+ return false;
39
+ }
40
+ }
41
+ return levels.length === parts.length;
42
+ }
43
+ //# sourceMappingURL=pattern.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pattern.js","sourceRoot":"","sources":["../src/pattern.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,KAAa;IACrC,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACpD,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,cAAc,CAAC,OAAe,EAAE,KAAa;IAC3D,IAAI,OAAO,KAAK,KAAK,EAAE,CAAC;QACtB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC/B,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;QAC9C,IAAI,KAAK,KAAK,GAAG,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC;QAC1B,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,KAAK,KAAK,GAAG,IAAI,KAAK,KAAK,IAAI,CAAC,EAAE,CAAC;YAC5D,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,CAAC;AACxC,CAAC","sourcesContent":["/**\n * Topic patterns for wildcard subscriptions: a topic name in which a whole\n * level may be `+` (any one level) and the last level may be `#` (that\n * level and everything below it). Mirrors `popsub_protocol::topics`.\n *\n * @module\n */\n\n/**\n * Whether a string has a wildcard, so it is a pattern and not a plain topic name.\n *\n * @param topic - The string.\n * @returns True when it contains `+` or `#`.\n */\nexport function isPattern(topic: string): boolean {\n return topic.includes(\"+\") || topic.includes(\"#\");\n}\n\n/**\n * Whether a topic matches a pattern. `+` stands for exactly one level and\n * `#`, which ends a pattern, for the rest of the topic, including nothing\n * (`orders/#` matches `orders`).\n *\n * @param pattern - The pattern.\n * @param topic - The topic name.\n * @returns True when the topic matches.\n */\nexport function matchesPattern(pattern: string, topic: string): boolean {\n if (pattern === topic) {\n return true;\n }\n const levels = pattern.split(\"/\");\n const parts = topic.split(\"/\");\n for (const [index, level] of levels.entries()) {\n if (level === \"#\") {\n return true;\n }\n const part = parts[index];\n if (part === undefined || (level !== \"+\" && level !== part)) {\n return false;\n }\n }\n return levels.length === parts.length;\n}\n"]}