@eliware/mail-client 15.0.3 → 17.0.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/AGENTS.md +1 -3
- package/README.md +1 -1
- package/RELEASE_NOTES.md +19 -0
- package/docs/api.md +18 -13
- package/docs/package.md +2 -2
- package/docs/troubleshooting.md +2 -2
- package/docs/usage.md +11 -6
- package/examples/README.md +14 -3
- package/examples/basic.mjs +3 -1
- package/examples/mail-client-smoke.mjs +3 -1
- package/package.json +4 -4
- package/specs/directives.yaml +10 -7
- package/src/index.browser.mjs +4 -2
- package/src/index.d.ts +24 -3
- package/src/index.mjs +5 -4
- package/src/mail/api/error.mjs +3 -1
- package/src/mail/api/methods.mjs +11 -6
- package/src/mail/client.mjs +6 -4
- package/src/mail/event/{connection-logging.mjs → connection/logging.mjs} +3 -1
- package/src/mail/event/connection/state.mjs +35 -0
- package/src/mail/event/connection.mjs +47 -47
- package/src/mail/event/processor.mjs +4 -2
- package/src/mail/event/reconnect-scheduler.mjs +42 -0
- package/src/mail/event/token-request.mjs +32 -0
- package/src/mail/ready-state.mjs +3 -1
- package/src/mail/transport/base-url.mjs +3 -1
- package/src/mail/transport.mjs +11 -8
- package/src/mail/websocket/address.mjs +3 -1
- package/src/mail/websocket/cursor.mjs +3 -1
- package/src/mail/websocket/frames.mjs +3 -1
- package/src/mail/websocket/listeners.mjs +3 -1
- package/src/mail/websocket/options.mjs +6 -2
- package/src/mail/websocket/session.mjs +11 -4
package/AGENTS.md
CHANGED
|
@@ -41,8 +41,6 @@ Run focused tests first during development.
|
|
|
41
41
|
Run one test file with `npm test -- tests/path/to/example.test.mjs`.
|
|
42
42
|
Run multiple test files with `npm test -- tests/path/to/first.test.mjs tests/path/to/second.test.mjs`.
|
|
43
43
|
Prevent repeated full-suite runs during development.
|
|
44
|
-
Run the full `npm test` suite for final validation before a commit
|
|
45
|
-
|
|
46
|
-
## npm publication
|
|
44
|
+
Run the full `npm test` suite for final validation before a commit.
|
|
47
45
|
|
|
48
46
|
Run `npm run pack` to check package contents. Follow approved release steps before publication.
|
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ Call the mail-server API from Node.js and browser applications. Receive WebSocke
|
|
|
27
27
|
|
|
28
28
|
## Requirements
|
|
29
29
|
|
|
30
|
-
Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSignal, and
|
|
30
|
+
Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSignal, URL, and WebSocket APIs.
|
|
31
31
|
|
|
32
32
|
## Setup
|
|
33
33
|
|
package/RELEASE_NOTES.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Release Notes
|
|
2
2
|
|
|
3
|
+
## 17.0.0 — 2026-12-06
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Expose event connection states through `connection.state` and the `onState` callback.
|
|
8
|
+
- Pass an `AbortSignal` to token providers. Abort it when a connection closes, a request times out, or the caller cancels a request.
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
|
|
12
|
+
- Change package root exports from named exports to a default-exported object. Import the default object. Read `createMailClient` and `MailApiError` from it.
|
|
13
|
+
- Use `@eliware/common/log` and remove the direct `@eliware/log` dependency.
|
|
14
|
+
- Require server authentication and event messages to use JSON text WebSocket frames. Reject binary frames.
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
|
|
18
|
+
- Prevent duplicate reconnect timers from opening multiple event connections.
|
|
19
|
+
- Validate message IDs before validating Discord link data.
|
|
20
|
+
- Apply HTTP timeouts and caller cancellation while the token provider runs.
|
|
21
|
+
|
|
3
22
|
## 15.0.3 — 2026-10-30
|
|
4
23
|
|
|
5
24
|
### Added
|
package/docs/api.md
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
# API reference
|
|
2
2
|
|
|
3
|
-
The package root
|
|
3
|
+
The package root provides `createMailClient` and `MailApiError` through its default export. The TypeScript declarations describe these properties.
|
|
4
4
|
|
|
5
5
|
## Create a client
|
|
6
6
|
|
|
7
7
|
Call `createMailClient(options)` to create an HTTP and WebSocket client.
|
|
8
8
|
|
|
9
|
-
| Option | Required | Default
|
|
10
|
-
| ---------------- | -------- |
|
|
11
|
-
| `baseUrl` | Yes | None
|
|
12
|
-
| `getAccessToken` | Yes | None
|
|
13
|
-
| `fetchImpl` | No | `globalThis.fetch`
|
|
14
|
-
| `WebSocketImpl` | No | `globalThis.WebSocket`
|
|
15
|
-
| `timeoutMs` | No | `15000`
|
|
16
|
-
| `logger` | No | Node.js: `@eliware/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
|
|
9
|
+
| Option | Required | Default | Description |
|
|
10
|
+
| ---------------- | -------- | ----------------------------------------------- | ---------------------------------------------- |
|
|
11
|
+
| `baseUrl` | Yes | None | HTTP or HTTPS base address for mail-server. |
|
|
12
|
+
| `getAccessToken` | Yes | None | Returns a bearer token as a string or promise. |
|
|
13
|
+
| `fetchImpl` | No | `globalThis.fetch` | Supplies the Fetch function for HTTP requests. |
|
|
14
|
+
| `WebSocketImpl` | No | `globalThis.WebSocket` | Supplies the WebSocket constructor. |
|
|
15
|
+
| `timeoutMs` | No | `15000` | Sets the timeout for each HTTP request. |
|
|
16
|
+
| `logger` | No | Node.js: `@eliware/common/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
|
|
17
17
|
|
|
18
18
|
Use an HTTP or HTTPS base address without a path, query, fragment, user name, or password. The client resolves request paths on that address. A leading `//` becomes one root slash. Absolute URLs must use the configured address.
|
|
19
19
|
|
|
20
|
-
The token provider runs before each HTTP request and each new WebSocket connection. It must return a non-empty string. The client does not inspect token claims or refresh tokens by itself.
|
|
20
|
+
The token provider runs before each HTTP request and each new WebSocket connection. It must return a non-empty string. For WebSocket connections, the client passes an `AbortSignal` to the provider and aborts it when the connection closes. The client does not inspect token claims or refresh tokens by itself.
|
|
21
21
|
|
|
22
|
-
The client combines the request timeout with a caller-provided `AbortSignal`.
|
|
22
|
+
The client combines the request timeout with a caller-provided `AbortSignal`. It passes the combined signal to the token provider and Fetch. This stops token retrieval when the request times out or the caller aborts. The client does not retry failed requests.
|
|
23
23
|
|
|
24
24
|
## HTTP request methods
|
|
25
25
|
|
|
@@ -155,10 +155,13 @@ The client waits for this server frame before it delivers events:
|
|
|
155
155
|
{ "type": "authenticated" }
|
|
156
156
|
```
|
|
157
157
|
|
|
158
|
+
The server must send authentication and event messages as JSON text frames. The client rejects binary frames.
|
|
159
|
+
|
|
158
160
|
| Option | Default | Description |
|
|
159
161
|
| --------------------- | ------------- | ------------------------------------------------------------------------------ |
|
|
160
162
|
| `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
|
|
161
163
|
| `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
|
|
164
|
+
| `onState(change)` | No operation | Receives connection lifecycle state changes. |
|
|
162
165
|
| `logger` | Client logger | Overrides the logger for this event connection. |
|
|
163
166
|
| `after` | Live edge | Starts event replay after a decimal cursor. |
|
|
164
167
|
| `consumerId` | None | Sends `consumer_id` to the server and enables durable cursor acknowledgements. |
|
|
@@ -167,7 +170,9 @@ The client waits for this server frame before it delivers events:
|
|
|
167
170
|
| `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
|
|
168
171
|
| `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
|
|
169
172
|
|
|
170
|
-
The connection object exposes `ready`, `cursor`, and `close()`.
|
|
173
|
+
The connection object exposes `state`, `ready`, `cursor`, and `close()`. Its state is `connecting`, `authenticated`, `reconnecting`, `closed`, or `failed`. The optional `onState` callback receives each state change with its prior state and retry details when available. Callback errors do not stop the connection.
|
|
174
|
+
|
|
175
|
+
The `ready` promise resolves after the first authentication acknowledgement. When `autoReconnect` is enabled, retryable token-provider failures and socket closures keep `ready` pending while the client retries. After the first authentication, use `state` or `onState` to observe later disconnects and recovery. The promise rejects when retries stop before authentication, the token value is invalid, socket construction fails, or the caller closes the connection.
|
|
171
176
|
|
|
172
177
|
The server accepts cursors from `0` through the maximum Snowflake ID. It requires decimal strings without leading zeroes, except for `0` itself.
|
|
173
178
|
|
|
@@ -181,6 +186,6 @@ The event has `event_id`, `cursor`, `event_type`, `occurred_at`, and `payload` f
|
|
|
181
186
|
|
|
182
187
|
## Runtime logging
|
|
183
188
|
|
|
184
|
-
The Node.js entry uses timestamped JSON logs through `@eliware/log` by default. Set `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL` to `debug` to enable debug records. The browser entry has no Node-only logging import and uses a silent logger by default. Supply an object with `debug`, `warn`, and `error` methods to inject a logger.
|
|
189
|
+
The Node.js entry uses timestamped JSON logs through `@eliware/common/log` by default. Set `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL` to `debug` to enable debug records. The browser entry has no Node-only logging import and uses a silent logger by default. Supply an object with `debug`, `warn`, and `error` methods to inject a logger.
|
|
185
190
|
|
|
186
191
|
The client logs HTTP methods, response statuses, durations, error names, request IDs, and WebSocket lifecycle details. It does not log bearer tokens, message bodies, attachment bytes, event payloads, or full request addresses. Pass `logger` in event connection options to override the client logger for a WebSocket connection.
|
package/docs/package.md
CHANGED
|
@@ -10,9 +10,9 @@ npm install @eliware/mail-client
|
|
|
10
10
|
|
|
11
11
|
The package supports Node.js 26 or later. Browser applications use Fetch, Headers, AbortSignal, URL, and WebSocket APIs. Use a bundler that honors the package `browser` export condition to select the browser entry.
|
|
12
12
|
|
|
13
|
-
The package root
|
|
13
|
+
The package root provides `createMailClient` and `MailApiError` through its default export. It includes TypeScript declarations at `src/index.d.ts`. Node.js uses `src/index.mjs`. Browser builds use `src/index.browser.mjs` and a silent logger by default.
|
|
14
14
|
|
|
15
|
-
The Node.js entry uses `@eliware/log`
|
|
15
|
+
The Node.js entry uses `@eliware/common/log` from the `@eliware/common` runtime dependency. The browser entry does not import the Node.js logger. Both entries expose the same client API.
|
|
16
16
|
|
|
17
17
|
## Environment values
|
|
18
18
|
|
package/docs/troubleshooting.md
CHANGED
|
@@ -18,7 +18,7 @@ Allow the browser site address for both HTTP and WebSocket access. Check the bro
|
|
|
18
18
|
|
|
19
19
|
## WebSocket events are missing
|
|
20
20
|
|
|
21
|
-
Wait for `connection.ready` before treating the connection as authenticated. The server must send `{"type":"authenticated"}` before it sends events.
|
|
21
|
+
Wait for `connection.ready` before treating the first connection as authenticated. Read `connection.state` or use `onState` to monitor later reconnects. The server must send `{"type":"authenticated"}` before it sends events.
|
|
22
22
|
|
|
23
23
|
Check that the token provider returns a valid token when mail-client opens or reconnects a socket. Refresh browser tokens before they expire.
|
|
24
24
|
|
|
@@ -26,7 +26,7 @@ Check the `onError` callback for socket, event handler, or acknowledgement failu
|
|
|
26
26
|
|
|
27
27
|
## Debug logs are missing
|
|
28
28
|
|
|
29
|
-
Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` before the Node.js process starts. The Node.js entry uses `@eliware/log` to write timestamped JSON records.
|
|
29
|
+
Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` before the Node.js process starts. The Node.js entry uses `@eliware/common/log` to write timestamped JSON records.
|
|
30
30
|
|
|
31
31
|
The browser entry stays silent by default. Pass a logger with `debug`, `warn`, and `error` methods to receive browser-side records.
|
|
32
32
|
|
package/docs/usage.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Usage guide
|
|
2
2
|
|
|
3
|
-
Use `@eliware/mail-client` to call the mail-server HTTP API and receive mail events through WebSocket. The library works in Node.js 26 or later and
|
|
3
|
+
Use `@eliware/mail-client` to call the mail-server HTTP API and receive mail events through WebSocket. The library works in Node.js 26 or later and in browsers that provide the required web APIs.
|
|
4
4
|
|
|
5
5
|
## Install the package
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Install the package in the application that calls mail-server:
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
10
|
npm install @eliware/mail-client
|
|
@@ -27,7 +27,9 @@ EliD sign-in belongs to mail-web. This package does not run OAuth flows and does
|
|
|
27
27
|
Pass the mail-server base address and a token provider. The client calls the provider for every HTTP request and each new WebSocket connection.
|
|
28
28
|
|
|
29
29
|
```js
|
|
30
|
-
import
|
|
30
|
+
import mailClient from "@eliware/mail-client";
|
|
31
|
+
|
|
32
|
+
const { createMailClient } = mailClient;
|
|
31
33
|
|
|
32
34
|
const mail = createMailClient({
|
|
33
35
|
baseUrl: process.env.MAIL_API_URL,
|
|
@@ -110,12 +112,13 @@ const events = browserMail.connectEvents({
|
|
|
110
112
|
}
|
|
111
113
|
},
|
|
112
114
|
onError: (error) => logger.error("Mail event connection failed", { error }),
|
|
115
|
+
onState: ({ state }) => updateConnectionStatus(state),
|
|
113
116
|
});
|
|
114
117
|
|
|
115
118
|
await events.ready;
|
|
116
119
|
```
|
|
117
120
|
|
|
118
|
-
The server sends `{"type":"authenticated"}` before it sends events. The client resolves `ready` after it receives that frame. If a retryable failure occurs first, `ready` stays pending until authentication succeeds or retries stop.
|
|
121
|
+
The server sends `{"type":"authenticated"}` before it sends events. The client resolves `ready` after it receives that frame. If a retryable failure occurs first, `ready` stays pending until authentication succeeds or retries stop. Read `events.state` or use `onState` to monitor later disconnects and recovery after the first authentication.
|
|
119
122
|
|
|
120
123
|
Events are notification signals. They can repeat and do not include complete message bodies or attachment bytes. Read current message data through the HTTP API. Make event handlers safe to run more than once.
|
|
121
124
|
|
|
@@ -137,7 +140,7 @@ Do not set `after` when you set `consumerId`. The server uses the durable consum
|
|
|
137
140
|
|
|
138
141
|
Without `consumerId`, the client tracks the cursor in memory only. The client includes its current cursor when it reconnects. Store progress with `consumerId` when an application must continue after a new process starts.
|
|
139
142
|
|
|
140
|
-
The client reconnects after unexpected socket closure or a token-provider failure by default. Set `autoReconnect` to `false` to disable reconnects. Call `events.close()` to stop the connection and its reconnect timer.
|
|
143
|
+
The client reconnects after unexpected socket closure or a token-provider failure by default. It reports `connecting`, `authenticated`, `reconnecting`, `closed`, and `failed` states. Set `autoReconnect` to `false` to disable reconnects. Call `events.close()` to stop the connection and its reconnect timer.
|
|
141
144
|
|
|
142
145
|
## Report errors
|
|
143
146
|
|
|
@@ -149,7 +152,7 @@ Use `onError` for WebSocket, event-handler, and event-acknowledgement failures.
|
|
|
149
152
|
|
|
150
153
|
## Configure logging
|
|
151
154
|
|
|
152
|
-
The Node.js entry uses timestamped JSON logs through `@eliware/log` by default. Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` to enable debug records. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
|
|
155
|
+
The Node.js entry uses timestamped JSON logs through `@eliware/common/log` by default. Set `MAIL_CLIENT_LOG_LEVEL=debug` or `LOG_LEVEL=debug` to enable debug records. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
|
|
153
156
|
|
|
154
157
|
```js
|
|
155
158
|
const mail = createMailClient({
|
|
@@ -172,3 +175,5 @@ npm run typecheck
|
|
|
172
175
|
npm run smoke
|
|
173
176
|
npm run pack
|
|
174
177
|
```
|
|
178
|
+
|
|
179
|
+
The smoke check starts a local HTTP server and a fake WebSocket. It checks the browser entry without a live mail-server or credentials.
|
package/examples/README.md
CHANGED
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
# Examples
|
|
2
2
|
|
|
3
3
|
The [basic example](basic.mjs) sends an authenticated request to the mail API status route.
|
|
4
|
+
The [smoke check](mail-client-smoke.mjs) uses a local HTTP server and a fake WebSocket.
|
|
4
5
|
|
|
5
|
-
##
|
|
6
|
+
## Basic example
|
|
7
|
+
|
|
8
|
+
### Prerequisites
|
|
6
9
|
|
|
7
10
|
Use Node.js 26 or later. Set `MAIL_API_URL` and `MAIL_API_TOKEN` in the local environment. Do not commit credentials.
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
### Command
|
|
10
13
|
|
|
11
14
|
Run `node examples/basic.mjs` from the repository root.
|
|
12
15
|
|
|
13
|
-
|
|
16
|
+
### Expected result
|
|
14
17
|
|
|
15
18
|
The example prints the JSON response from the configured mail API. The API must be reachable and the token must have access to the status route.
|
|
19
|
+
|
|
20
|
+
## Smoke check
|
|
21
|
+
|
|
22
|
+
The smoke check needs no credentials or live mail service. It starts a local API server and fake WebSocket, then checks token requests, status requests, authentication, and event delivery.
|
|
23
|
+
|
|
24
|
+
Run `npm run smoke` from the package root.
|
|
25
|
+
|
|
26
|
+
The check prints `mail-client smoke check passed` when each operation succeeds.
|
package/examples/basic.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
|
-
import
|
|
3
|
+
import mailClient from "../src/index.browser.mjs";
|
|
4
|
+
|
|
5
|
+
const { createMailClient } = mailClient;
|
|
4
6
|
|
|
5
7
|
class SmokeSocket {
|
|
6
8
|
static current;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eliware/mail-client",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "17.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Mail client library for the Eliware mail platform.",
|
|
6
6
|
"keywords": [
|
|
@@ -41,10 +41,10 @@
|
|
|
41
41
|
"node": ">=26"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@eliware/
|
|
44
|
+
"@eliware/common": "^17.0.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@eliware/test": "^
|
|
47
|
+
"@eliware/test": "^17.0.0",
|
|
48
48
|
"typescript": "^7.0.2"
|
|
49
49
|
},
|
|
50
50
|
"jest": {
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"url": "https://github.com/eliware/mail-client/issues"
|
|
95
95
|
},
|
|
96
96
|
"eliware": {
|
|
97
|
-
"id": "E-
|
|
97
|
+
"id": "E-1051",
|
|
98
98
|
"apply": [
|
|
99
99
|
"general",
|
|
100
100
|
"library",
|
package/specs/directives.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
version: "
|
|
1
|
+
version: "17.0"
|
|
2
2
|
description: Requirements for the shared Eliware mail API client library.
|
|
3
3
|
directives:
|
|
4
|
-
- id: E-
|
|
4
|
+
- id: E-1051.0
|
|
5
5
|
dos:
|
|
6
6
|
- Provide HTTP API and WebSocket clients for Node.js and browser applications.
|
|
7
7
|
- Publish the native ESM package as `@eliware/mail-client` with TypeScript declarations.
|
|
@@ -14,7 +14,7 @@ directives:
|
|
|
14
14
|
- Do not depend on `@eliware/elid-client` or run OAuth flows.
|
|
15
15
|
- Do not rewrite mail-cli, mail-discord, or mail-web in this repository.
|
|
16
16
|
|
|
17
|
-
- id: E-
|
|
17
|
+
- id: E-1051.1
|
|
18
18
|
dos:
|
|
19
19
|
- Support mail-server routes for reads, searches, updates, sends, deletes, and send actions.
|
|
20
20
|
- Save and find inbound and sent Discord links through authenticated mail-server routes.
|
|
@@ -28,7 +28,7 @@ directives:
|
|
|
28
28
|
- Do not reshape API response bodies without documenting the change.
|
|
29
29
|
- Do not retry a send without a stable idempotency key.
|
|
30
30
|
|
|
31
|
-
- id: E-
|
|
31
|
+
- id: E-1051.2
|
|
32
32
|
dos:
|
|
33
33
|
- Use separate static API keys for mail-discord and mail-web server deployments.
|
|
34
34
|
- Allow separate long-lived API keys for every mail-cli installation.
|
|
@@ -48,14 +48,17 @@ directives:
|
|
|
48
48
|
- Do not add multi-user access rules or per-user mailbox scopes.
|
|
49
49
|
- Do not store browser tokens in durable browser storage.
|
|
50
50
|
|
|
51
|
-
- id: E-
|
|
51
|
+
- id: E-1051.3
|
|
52
52
|
dos:
|
|
53
53
|
- Authenticate WebSocket sessions after the browser opens each connection.
|
|
54
54
|
- Send `{"type":"authenticate","token":"..."}` as the first WebSocket message.
|
|
55
|
+
- Require server authentication and event messages to use JSON text frames.
|
|
55
56
|
- Wait for `{"type":"authenticated"}` before delivering events to callers.
|
|
56
57
|
- Support different mail-server and mail-web domains without tokens in WebSocket URLs.
|
|
57
58
|
- Reconnect safely and continue events from the last acknowledged cursor.
|
|
58
59
|
- Retry WebSocket setup after token provider failures when automatic reconnect is enabled.
|
|
60
|
+
- Expose connection states so hosts can monitor authentication, retries, and terminal
|
|
61
|
+
failures.
|
|
59
62
|
- Let stable consumer IDs acknowledge processed event cursors through the HTTP API.
|
|
60
63
|
- Send a stable consumer ID as `consumer_id` when opening a durable WebSocket connection.
|
|
61
64
|
- Use the server-stored consumer cursor for durable WebSocket event replay.
|
|
@@ -67,9 +70,9 @@ directives:
|
|
|
67
70
|
- Do not mark a WebSocket session authenticated before the server accepts its first message.
|
|
68
71
|
- Do not use event notifications as complete message data.
|
|
69
72
|
|
|
70
|
-
- id: E-
|
|
73
|
+
- id: E-1051.4
|
|
71
74
|
dos:
|
|
72
|
-
- Use `@eliware/log`
|
|
75
|
+
- Use `@eliware/common/log` for timestamped JSON logs in the Node.js package entry.
|
|
73
76
|
- Set the default log level through `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
|
|
74
77
|
- Accept an injected logger with `debug`, `warn`, and `error` methods for HTTP and WebSocket
|
|
75
78
|
events.
|
package/src/index.browser.mjs
CHANGED
package/src/index.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface WebSocketFactory {
|
|
|
19
19
|
|
|
20
20
|
export interface MailClientOptions {
|
|
21
21
|
baseUrl: string;
|
|
22
|
-
getAccessToken: () => string | Promise<string>;
|
|
22
|
+
getAccessToken: (options?: { signal: AbortSignal }) => string | Promise<string>;
|
|
23
23
|
fetchImpl?: typeof fetch;
|
|
24
24
|
WebSocketImpl?: WebSocketFactory;
|
|
25
25
|
timeoutMs?: number;
|
|
@@ -39,6 +39,7 @@ export interface EventConnectionOptions {
|
|
|
39
39
|
consumerId?: string;
|
|
40
40
|
onEvent(event: MailEvent): void | Promise<void>;
|
|
41
41
|
onError?(error: Error): void;
|
|
42
|
+
onState?(change: EventConnectionStateChange): void;
|
|
42
43
|
autoReconnect?: boolean;
|
|
43
44
|
retryDelayMs?: number;
|
|
44
45
|
maxReconnectDelayMs?: number;
|
|
@@ -46,7 +47,20 @@ export interface EventConnectionOptions {
|
|
|
46
47
|
logger?: MailLogger;
|
|
47
48
|
}
|
|
48
49
|
|
|
50
|
+
export type EventConnectionState =
|
|
51
|
+
"connecting" | "authenticated" | "reconnecting" | "closed" | "failed";
|
|
52
|
+
|
|
53
|
+
export interface EventConnectionStateChange {
|
|
54
|
+
state: EventConnectionState;
|
|
55
|
+
previousState: EventConnectionState;
|
|
56
|
+
closeCode?: number;
|
|
57
|
+
retryDelayMs?: number;
|
|
58
|
+
attempt?: number;
|
|
59
|
+
error?: Error;
|
|
60
|
+
}
|
|
61
|
+
|
|
49
62
|
export interface EventConnection {
|
|
63
|
+
readonly state: EventConnectionState;
|
|
50
64
|
readonly ready: Promise<void>;
|
|
51
65
|
readonly cursor: string | null;
|
|
52
66
|
close(): void;
|
|
@@ -162,11 +176,18 @@ export interface MailClient {
|
|
|
162
176
|
connectEvents(options: EventConnectionOptions): EventConnection;
|
|
163
177
|
}
|
|
164
178
|
|
|
165
|
-
|
|
179
|
+
declare class MailApiError extends Error {
|
|
166
180
|
readonly status: number;
|
|
167
181
|
readonly code: string;
|
|
168
182
|
readonly requestId: string | null;
|
|
169
183
|
readonly payload: unknown;
|
|
170
184
|
}
|
|
171
185
|
|
|
172
|
-
|
|
186
|
+
declare function createMailClient(options: MailClientOptions): MailClient;
|
|
187
|
+
|
|
188
|
+
declare const mailClient: {
|
|
189
|
+
createMailClient: typeof createMailClient;
|
|
190
|
+
MailApiError: typeof MailApiError;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
export default mailClient;
|
package/src/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { createLogger } from "@eliware/log";
|
|
2
|
-
import
|
|
1
|
+
import { createLogger } from "@eliware/common/log";
|
|
2
|
+
import createClient from "./mail/client.mjs";
|
|
3
|
+
import MailApiError from "./mail/api/error.mjs";
|
|
3
4
|
|
|
4
5
|
const defaultLogger = createLogger({
|
|
5
6
|
level: process.env.MAIL_CLIENT_LOG_LEVEL ?? process.env.LOG_LEVEL ?? "info",
|
|
@@ -8,8 +9,8 @@ const defaultLogger = createLogger({
|
|
|
8
9
|
keys: ["token", "access_token", "authorization", "body", "payload", "attachments"],
|
|
9
10
|
});
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
function createMailClient(options) {
|
|
12
13
|
return createClient({ ...options, logger: options?.logger ?? defaultLogger });
|
|
13
14
|
}
|
|
14
15
|
|
|
15
|
-
export { MailApiError }
|
|
16
|
+
export default { createMailClient, MailApiError };
|
package/src/mail/api/error.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
class MailApiError extends Error {
|
|
2
2
|
constructor(status, payload, headers) {
|
|
3
3
|
const apiError = payload?.error;
|
|
4
4
|
super(apiError?.message ?? `Mail API request failed with HTTP ${status}`);
|
|
@@ -9,3 +9,5 @@ export class MailApiError extends Error {
|
|
|
9
9
|
this.payload = payload;
|
|
10
10
|
}
|
|
11
11
|
}
|
|
12
|
+
|
|
13
|
+
export default MailApiError;
|
package/src/mail/api/methods.mjs
CHANGED
|
@@ -20,7 +20,6 @@ function itemPath(collection, id, suffix = "") {
|
|
|
20
20
|
}
|
|
21
21
|
|
|
22
22
|
const maxDiscordSnowflake = 18_446_744_073_709_551_615n;
|
|
23
|
-
|
|
24
23
|
function validateDiscordIds(channelId, messageId) {
|
|
25
24
|
for (const [name, value] of [
|
|
26
25
|
["discordChannelId", channelId],
|
|
@@ -36,7 +35,7 @@ function validateDiscordIds(channelId, messageId) {
|
|
|
36
35
|
}
|
|
37
36
|
}
|
|
38
37
|
|
|
39
|
-
|
|
38
|
+
function createApiMethods({ request, requestJson }) {
|
|
40
39
|
const json = (method, path, body) =>
|
|
41
40
|
requestJson(path, { method, ...(body === undefined ? {} : { body }) });
|
|
42
41
|
const messages = {
|
|
@@ -47,9 +46,11 @@ export function createApiMethods({ request, requestJson }) {
|
|
|
47
46
|
thread: (id) => requestJson(itemPath("messages", id, "/thread")),
|
|
48
47
|
update: (id, changes) => json("PATCH", itemPath("messages", id), changes),
|
|
49
48
|
delete: (id) => json("DELETE", itemPath("messages", id)),
|
|
50
|
-
saveDiscordLink: (id,
|
|
49
|
+
saveDiscordLink: (id, link = {}) => {
|
|
50
|
+
const path = itemPath("messages", id, "/discord-links"),
|
|
51
|
+
{ discordChannelId, discordMessageId } = link ?? {};
|
|
51
52
|
validateDiscordIds(discordChannelId, discordMessageId);
|
|
52
|
-
return json("PUT",
|
|
53
|
+
return json("PUT", path, {
|
|
53
54
|
discord_channel_id: discordChannelId,
|
|
54
55
|
discord_message_id: discordMessageId,
|
|
55
56
|
});
|
|
@@ -74,9 +75,11 @@ export function createApiMethods({ request, requestJson }) {
|
|
|
74
75
|
confirm_duplicate_risk: true,
|
|
75
76
|
});
|
|
76
77
|
},
|
|
77
|
-
saveDiscordLink: (id,
|
|
78
|
+
saveDiscordLink: (id, link = {}) => {
|
|
79
|
+
const path = itemPath("sent", id, "/discord-links"),
|
|
80
|
+
{ discordChannelId, discordMessageId } = link ?? {};
|
|
78
81
|
validateDiscordIds(discordChannelId, discordMessageId);
|
|
79
|
-
return json("PUT",
|
|
82
|
+
return json("PUT", path, {
|
|
80
83
|
discord_channel_id: discordChannelId,
|
|
81
84
|
discord_message_id: discordMessageId,
|
|
82
85
|
});
|
|
@@ -143,3 +146,5 @@ export function createApiMethods({ request, requestJson }) {
|
|
|
143
146
|
events,
|
|
144
147
|
};
|
|
145
148
|
}
|
|
149
|
+
|
|
150
|
+
export default createApiMethods;
|
package/src/mail/client.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
1
|
+
import createApiMethods from "./api/methods.mjs";
|
|
2
|
+
import createEventConnection from "./event/connection.mjs";
|
|
3
|
+
import createTransport from "./transport.mjs";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
function createMailClient(options = {}) {
|
|
6
6
|
const transport = createTransport(options);
|
|
7
7
|
const api = createApiMethods(transport);
|
|
8
8
|
return {
|
|
@@ -20,3 +20,5 @@ export function createMailClient(options = {}) {
|
|
|
20
20
|
},
|
|
21
21
|
};
|
|
22
22
|
}
|
|
23
|
+
|
|
24
|
+
export default createMailClient;
|
|
@@ -5,7 +5,7 @@ function errorName(error) {
|
|
|
5
5
|
return typeof error?.name === "string" ? error.name : "Error";
|
|
6
6
|
}
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
function createEventConnectionLogger(logger = silentLogger) {
|
|
9
9
|
function write(level, message, metadata) {
|
|
10
10
|
try {
|
|
11
11
|
logger[level](message, metadata);
|
|
@@ -69,3 +69,5 @@ export function createEventConnectionLogger(logger = silentLogger) {
|
|
|
69
69
|
},
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
+
|
|
73
|
+
export default createEventConnectionLogger;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
function createEventConnectionState({ onState, onError, settleReady }) {
|
|
2
|
+
let state = "connecting";
|
|
3
|
+
|
|
4
|
+
function transition(nextState, details = {}) {
|
|
5
|
+
if (state === nextState) return;
|
|
6
|
+
const previousState = state;
|
|
7
|
+
state = nextState;
|
|
8
|
+
try {
|
|
9
|
+
onState({ state, previousState, ...details });
|
|
10
|
+
} catch {}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function report(error) {
|
|
14
|
+
try {
|
|
15
|
+
onError(error);
|
|
16
|
+
} catch {}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function fail(error) {
|
|
20
|
+
transition("failed", { error });
|
|
21
|
+
report(error);
|
|
22
|
+
settleReady(error);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return {
|
|
26
|
+
get state() {
|
|
27
|
+
return state;
|
|
28
|
+
},
|
|
29
|
+
transition,
|
|
30
|
+
report,
|
|
31
|
+
fail,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export default createEventConnectionState;
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import
|
|
4
|
-
import
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
import createWebSocketSession from "../websocket/session.mjs";
|
|
2
|
+
import socketUrl from "../websocket/address.mjs";
|
|
3
|
+
import validateEventOptions from "../websocket/options.mjs";
|
|
4
|
+
import createEventConnectionLogger from "./connection/logging.mjs";
|
|
5
|
+
import createEventProcessor from "./processor.mjs";
|
|
6
|
+
import createReadyState from "../ready-state.mjs";
|
|
7
|
+
import createEventConnectionState from "./connection/state.mjs";
|
|
8
|
+
import createReconnectScheduler from "./reconnect-scheduler.mjs";
|
|
9
|
+
import createTokenRequest from "./token-request.mjs";
|
|
10
|
+
export default function createEventConnection({
|
|
9
11
|
baseUrl,
|
|
10
12
|
getAccessToken,
|
|
11
13
|
acknowledgeEvent,
|
|
@@ -14,6 +16,7 @@ export function createEventConnection({
|
|
|
14
16
|
consumerId,
|
|
15
17
|
onEvent,
|
|
16
18
|
onError = () => {},
|
|
19
|
+
onState = () => {},
|
|
17
20
|
autoReconnect = true,
|
|
18
21
|
retryDelayMs = 500,
|
|
19
22
|
maxReconnectDelayMs = 30_000,
|
|
@@ -25,6 +28,7 @@ export function createEventConnection({
|
|
|
25
28
|
WebSocketImpl,
|
|
26
29
|
onEvent,
|
|
27
30
|
onError,
|
|
31
|
+
onState,
|
|
28
32
|
consumerId,
|
|
29
33
|
acknowledgeEvent,
|
|
30
34
|
logger,
|
|
@@ -32,31 +36,14 @@ export function createEventConnection({
|
|
|
32
36
|
maxReconnectDelayMs,
|
|
33
37
|
after,
|
|
34
38
|
});
|
|
35
|
-
let cursor = after ?? null
|
|
36
|
-
|
|
37
|
-
let
|
|
38
|
-
|
|
39
|
-
let attempt = 0;
|
|
40
|
-
let authenticated = false;
|
|
39
|
+
let cursor = after ?? null,
|
|
40
|
+
socket;
|
|
41
|
+
let stopped = false,
|
|
42
|
+
authenticated = false;
|
|
41
43
|
let processing = Promise.resolve();
|
|
42
44
|
const { ready, settle: settleReady } = createReadyState();
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
try {
|
|
46
|
-
onError(error);
|
|
47
|
-
} catch {}
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function scheduleReconnect(code) {
|
|
51
|
-
if (stopped || !autoReconnect || code === 1000 || code === 1008) return false;
|
|
52
|
-
const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
|
|
53
|
-
attempt += 1;
|
|
54
|
-
logs.reconnectScheduled(code, delay, attempt, cursor);
|
|
55
|
-
timer = setTimeout(connect, delay);
|
|
56
|
-
timer.unref?.();
|
|
57
|
-
return true;
|
|
58
|
-
}
|
|
59
|
-
|
|
45
|
+
const lifecycle = createEventConnectionState({ onState, onError, settleReady });
|
|
46
|
+
const tokenRequest = createTokenRequest(getAccessToken);
|
|
60
47
|
const processEvent = createEventProcessor({
|
|
61
48
|
getCursor: () => cursor,
|
|
62
49
|
setCursor: (value) => {
|
|
@@ -67,19 +54,19 @@ export function createEventConnection({
|
|
|
67
54
|
onEvent,
|
|
68
55
|
logs,
|
|
69
56
|
});
|
|
70
|
-
|
|
71
57
|
async function connect() {
|
|
72
58
|
if (stopped) return;
|
|
59
|
+
lifecycle.transition("connecting");
|
|
73
60
|
authenticated = false;
|
|
74
61
|
logs.started(cursor);
|
|
75
62
|
let token;
|
|
76
63
|
try {
|
|
77
|
-
token = await
|
|
64
|
+
token = await tokenRequest.read();
|
|
78
65
|
} catch (error) {
|
|
79
66
|
if (stopped) return;
|
|
80
67
|
logs.tokenProviderFailed(error);
|
|
81
|
-
|
|
82
|
-
|
|
68
|
+
if (!reconnect.schedule(1006, error)) lifecycle.fail(error);
|
|
69
|
+
else lifecycle.report(error);
|
|
83
70
|
return;
|
|
84
71
|
}
|
|
85
72
|
if (stopped) return;
|
|
@@ -87,8 +74,7 @@ export function createEventConnection({
|
|
|
87
74
|
const error = new TypeError("getAccessToken must return a non-empty bearer token");
|
|
88
75
|
stopped = true;
|
|
89
76
|
logs.invalidToken();
|
|
90
|
-
|
|
91
|
-
settleReady(error);
|
|
77
|
+
lifecycle.fail(error);
|
|
92
78
|
return;
|
|
93
79
|
}
|
|
94
80
|
try {
|
|
@@ -98,7 +84,8 @@ export function createEventConnection({
|
|
|
98
84
|
WebSocketImpl,
|
|
99
85
|
onAuthenticated: () => {
|
|
100
86
|
authenticated = true;
|
|
101
|
-
|
|
87
|
+
reconnect.reset();
|
|
88
|
+
lifecycle.transition("authenticated");
|
|
102
89
|
logs.authenticated(cursor);
|
|
103
90
|
settleReady();
|
|
104
91
|
},
|
|
@@ -107,41 +94,54 @@ export function createEventConnection({
|
|
|
107
94
|
.then(() => (stopped ? undefined : processEvent(event)))
|
|
108
95
|
.catch((error) => {
|
|
109
96
|
logs.eventFailed(event, error);
|
|
110
|
-
|
|
97
|
+
lifecycle.fail(error);
|
|
111
98
|
stopped = true;
|
|
112
|
-
settleReady(error);
|
|
113
99
|
socket.close(1011, "event processing failed");
|
|
114
100
|
});
|
|
115
101
|
},
|
|
116
102
|
onClose: (code) => {
|
|
117
103
|
logs.closed(code, authenticated, cursor);
|
|
118
|
-
const reconnecting =
|
|
119
|
-
if (!
|
|
104
|
+
const reconnecting = reconnect.schedule(code);
|
|
105
|
+
if (!reconnecting) {
|
|
106
|
+
lifecycle.transition(code === 1000 ? "closed" : "failed", { closeCode: code });
|
|
120
107
|
settleReady(new Error(`WebSocket authentication closed with code ${code}`));
|
|
121
108
|
}
|
|
122
109
|
},
|
|
123
110
|
onError: (error) => {
|
|
124
111
|
logs.socketFailed(error);
|
|
125
|
-
report(error);
|
|
112
|
+
lifecycle.report(error);
|
|
126
113
|
},
|
|
127
114
|
});
|
|
128
115
|
} catch (error) {
|
|
129
116
|
stopped = true;
|
|
130
117
|
logs.startFailed(error);
|
|
131
|
-
|
|
132
|
-
settleReady(error);
|
|
118
|
+
lifecycle.fail(error);
|
|
133
119
|
}
|
|
134
120
|
}
|
|
135
|
-
|
|
121
|
+
const reconnect = createReconnectScheduler({
|
|
122
|
+
enabled: autoReconnect,
|
|
123
|
+
retryDelayMs,
|
|
124
|
+
maxReconnectDelayMs,
|
|
125
|
+
isStopped: () => stopped,
|
|
126
|
+
connect,
|
|
127
|
+
lifecycle,
|
|
128
|
+
logs,
|
|
129
|
+
getCursor: () => cursor,
|
|
130
|
+
});
|
|
136
131
|
void connect();
|
|
137
132
|
return {
|
|
138
133
|
ready,
|
|
134
|
+
get state() {
|
|
135
|
+
return lifecycle.state;
|
|
136
|
+
},
|
|
139
137
|
get cursor() {
|
|
140
138
|
return cursor;
|
|
141
139
|
},
|
|
142
140
|
close() {
|
|
143
141
|
stopped = true;
|
|
144
|
-
|
|
142
|
+
tokenRequest.cancel();
|
|
143
|
+
reconnect.cancel();
|
|
144
|
+
lifecycle.transition("closed");
|
|
145
145
|
logs.clientClosed(cursor);
|
|
146
146
|
settleReady(new Error("WebSocket connection closed by the client"));
|
|
147
147
|
socket?.close(1000, "client closed");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
1
|
+
import isValidCursor from "../websocket/cursor.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
function createEventProcessor({
|
|
4
4
|
getCursor,
|
|
5
5
|
setCursor,
|
|
6
6
|
consumerId,
|
|
@@ -25,3 +25,5 @@ export function createEventProcessor({
|
|
|
25
25
|
logs.eventCompleted(event?.event_type, eventCursor, consumerId !== undefined);
|
|
26
26
|
};
|
|
27
27
|
}
|
|
28
|
+
|
|
29
|
+
export default createEventProcessor;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
function createReconnectScheduler({
|
|
2
|
+
enabled,
|
|
3
|
+
retryDelayMs,
|
|
4
|
+
maxReconnectDelayMs,
|
|
5
|
+
isStopped,
|
|
6
|
+
connect,
|
|
7
|
+
lifecycle,
|
|
8
|
+
logs,
|
|
9
|
+
getCursor,
|
|
10
|
+
}) {
|
|
11
|
+
let attempt = 0;
|
|
12
|
+
let timer;
|
|
13
|
+
|
|
14
|
+
function schedule(code, error) {
|
|
15
|
+
if (isStopped() || !enabled || [1000, 1002, 1003, 1007, 1008, 1009, 1010].includes(code))
|
|
16
|
+
return false;
|
|
17
|
+
if (timer !== undefined) return true;
|
|
18
|
+
const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
|
|
19
|
+
attempt += 1;
|
|
20
|
+
lifecycle.transition("reconnecting", { closeCode: code, retryDelayMs: delay, attempt, error });
|
|
21
|
+
logs.reconnectScheduled(code, delay, attempt, getCursor());
|
|
22
|
+
timer = setTimeout(() => {
|
|
23
|
+
timer = undefined;
|
|
24
|
+
connect();
|
|
25
|
+
}, delay);
|
|
26
|
+
timer.unref?.();
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return {
|
|
31
|
+
schedule,
|
|
32
|
+
reset() {
|
|
33
|
+
attempt = 0;
|
|
34
|
+
},
|
|
35
|
+
cancel() {
|
|
36
|
+
if (timer) clearTimeout(timer);
|
|
37
|
+
timer = undefined;
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export default createReconnectScheduler;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
function createTokenRequest(getAccessToken, externalSignal) {
|
|
2
|
+
const controller = new AbortController();
|
|
3
|
+
const signal = externalSignal
|
|
4
|
+
? AbortSignal.any([controller.signal, externalSignal])
|
|
5
|
+
: controller.signal;
|
|
6
|
+
|
|
7
|
+
function read() {
|
|
8
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
9
|
+
let token;
|
|
10
|
+
try {
|
|
11
|
+
token = getAccessToken({ signal });
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
if (signal.aborted) return Promise.reject(signal.reason);
|
|
17
|
+
if (token === null || typeof token !== "object" || typeof token.then !== "function")
|
|
18
|
+
return token;
|
|
19
|
+
let onAbort;
|
|
20
|
+
const aborted = new Promise((_, reject) => {
|
|
21
|
+
onAbort = () => reject(signal.reason);
|
|
22
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
23
|
+
});
|
|
24
|
+
return Promise.race([token, aborted]).finally(() =>
|
|
25
|
+
signal.removeEventListener("abort", onAbort),
|
|
26
|
+
);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return { read, cancel: () => controller.abort() };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export default createTokenRequest;
|
package/src/mail/ready-state.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
function createReadyState() {
|
|
2
2
|
let settled = false;
|
|
3
3
|
let resolveReady;
|
|
4
4
|
let rejectReady;
|
|
@@ -17,3 +17,5 @@ export function createReadyState() {
|
|
|
17
17
|
|
|
18
18
|
return { ready, settle };
|
|
19
19
|
}
|
|
20
|
+
|
|
21
|
+
export default createReadyState;
|
package/src/mail/transport.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import MailApiError from "./api/error.mjs";
|
|
2
|
+
import normalizeBaseUrl from "./transport/base-url.mjs";
|
|
3
|
+
import createTokenRequest from "./event/token-request.mjs";
|
|
3
4
|
|
|
4
5
|
const defaultTimeoutMs = 15_000;
|
|
5
6
|
const noOperation = () => {};
|
|
@@ -23,7 +24,7 @@ async function errorPayload(response) {
|
|
|
23
24
|
}
|
|
24
25
|
}
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
function createTransport({
|
|
27
28
|
baseUrl,
|
|
28
29
|
getAccessToken,
|
|
29
30
|
fetchImpl = globalThis.fetch,
|
|
@@ -57,9 +58,13 @@ export function createTransport({
|
|
|
57
58
|
const method = String(options.method ?? "GET").toUpperCase();
|
|
58
59
|
const startedAt = Date.now();
|
|
59
60
|
logger.debug("Mail API request started", { method });
|
|
61
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
62
|
+
const signal = options.signal
|
|
63
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
64
|
+
: timeoutSignal;
|
|
60
65
|
let token;
|
|
61
66
|
try {
|
|
62
|
-
token = await getAccessToken();
|
|
67
|
+
token = await createTokenRequest(getAccessToken, signal).read();
|
|
63
68
|
} catch (error) {
|
|
64
69
|
logger.error("Mail API access token provider failed", {
|
|
65
70
|
method,
|
|
@@ -86,10 +91,6 @@ export function createTransport({
|
|
|
86
91
|
headers.set("content-type", "application/json");
|
|
87
92
|
}
|
|
88
93
|
|
|
89
|
-
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
90
|
-
const signal = options.signal
|
|
91
|
-
? AbortSignal.any([options.signal, timeoutSignal])
|
|
92
|
-
: timeoutSignal;
|
|
93
94
|
let response;
|
|
94
95
|
try {
|
|
95
96
|
response = await fetchImpl(url, { ...options, method, headers, body: requestBody, signal });
|
|
@@ -131,3 +132,5 @@ export function createTransport({
|
|
|
131
132
|
|
|
132
133
|
return { request, requestJson, baseUrl: apiOrigin };
|
|
133
134
|
}
|
|
135
|
+
|
|
136
|
+
export default createTransport;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
function socketUrl(baseUrl, cursor, consumerId) {
|
|
2
2
|
const url = new URL("/ws", baseUrl);
|
|
3
3
|
url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
|
|
4
4
|
if (cursor !== null) url.searchParams.set("after", cursor);
|
|
5
5
|
if (consumerId !== undefined) url.searchParams.set("consumer_id", consumerId);
|
|
6
6
|
return url.toString();
|
|
7
7
|
}
|
|
8
|
+
|
|
9
|
+
export default socketUrl;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
const maxSnowflakeCursor = 18_446_744_073_709_551_615n;
|
|
2
2
|
const decimalCursorPattern = /^(0|[1-9]\d{0,19})$/;
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
function isValidCursor(value) {
|
|
5
5
|
if (typeof value !== "string" || !decimalCursorPattern.test(value)) return false;
|
|
6
6
|
return BigInt(value) <= maxSnowflakeCursor;
|
|
7
7
|
}
|
|
8
|
+
|
|
9
|
+
export default isValidCursor;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
function eventData(value) {
|
|
2
2
|
const data = value?.data ?? value;
|
|
3
3
|
if (typeof data === "string") return data;
|
|
4
4
|
if (ArrayBuffer.isView(data)) return new TextDecoder().decode(data);
|
|
5
5
|
if (data instanceof ArrayBuffer) return new TextDecoder().decode(data);
|
|
6
6
|
throw new TypeError("WebSocket frame must contain JSON text");
|
|
7
7
|
}
|
|
8
|
+
|
|
9
|
+
export default eventData;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
function subscribe(socket, name, handler) {
|
|
2
2
|
if (typeof socket.addEventListener === "function") {
|
|
3
3
|
socket.addEventListener(name, handler);
|
|
4
4
|
return () => socket.removeEventListener?.(name, handler);
|
|
@@ -9,3 +9,5 @@ export function subscribe(socket, name, handler) {
|
|
|
9
9
|
}
|
|
10
10
|
throw new TypeError("WebSocket must support event listeners");
|
|
11
11
|
}
|
|
12
|
+
|
|
13
|
+
export default subscribe;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import
|
|
1
|
+
import isValidCursor from "./cursor.mjs";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
function validateEventOptions({
|
|
4
4
|
getAccessToken,
|
|
5
5
|
WebSocketImpl,
|
|
6
6
|
onEvent,
|
|
7
7
|
onError,
|
|
8
|
+
onState,
|
|
8
9
|
consumerId,
|
|
9
10
|
acknowledgeEvent,
|
|
10
11
|
logger,
|
|
@@ -18,6 +19,7 @@ export function validateEventOptions({
|
|
|
18
19
|
throw new TypeError("WebSocketImpl must be a constructor");
|
|
19
20
|
if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function");
|
|
20
21
|
if (typeof onError !== "function") throw new TypeError("onError must be a function");
|
|
22
|
+
if (typeof onState !== "function") throw new TypeError("onState must be a function");
|
|
21
23
|
if (
|
|
22
24
|
logger !== undefined &&
|
|
23
25
|
(typeof logger?.debug !== "function" ||
|
|
@@ -45,3 +47,5 @@ export function validateEventOptions({
|
|
|
45
47
|
throw new TypeError("after and consumerId cannot be used together");
|
|
46
48
|
}
|
|
47
49
|
}
|
|
50
|
+
|
|
51
|
+
export default validateEventOptions;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import eventData from "./frames.mjs";
|
|
2
|
+
import subscribe from "./listeners.mjs";
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
function createWebSocketSession({
|
|
5
5
|
url,
|
|
6
6
|
token,
|
|
7
7
|
WebSocketImpl,
|
|
@@ -17,7 +17,12 @@ export function createWebSocketSession({
|
|
|
17
17
|
});
|
|
18
18
|
subscribe(socket, "message", (value, isBinary = false) => {
|
|
19
19
|
const data = value?.data;
|
|
20
|
-
if (
|
|
20
|
+
if (
|
|
21
|
+
isBinary ||
|
|
22
|
+
(typeof Blob !== "undefined" && data instanceof Blob) ||
|
|
23
|
+
data instanceof ArrayBuffer ||
|
|
24
|
+
ArrayBuffer.isView(data)
|
|
25
|
+
) {
|
|
21
26
|
onError(new TypeError("WebSocket frames must use JSON text"));
|
|
22
27
|
socket.close(1002, "JSON text required");
|
|
23
28
|
return;
|
|
@@ -48,3 +53,5 @@ export function createWebSocketSession({
|
|
|
48
53
|
);
|
|
49
54
|
return socket;
|
|
50
55
|
}
|
|
56
|
+
|
|
57
|
+
export default createWebSocketSession;
|