@eliware/mail-client 15.0.1 → 15.0.3

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 CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  ## Project
4
4
 
5
- Build the shared mail-server API client library for Eliware.
5
+ See README.md for the repository purpose, owner, scope, and boundaries.
6
6
 
7
7
  ## Scope and boundaries
8
8
 
9
- Use specs/directives.yaml for repository scope and limits.
9
+ Keep repository requirements in specs/directives.yaml.
10
10
 
11
11
  ## Layout
12
12
 
@@ -33,7 +33,7 @@ Keep credentials, secret values, private data, and runtime state out of Git.
33
33
 
34
34
  ## Changes
35
35
 
36
- Keep each document in the repository that owns its content.
36
+ Keep each document in the repository that owns its content. Update its nearest index when you add a document.
37
37
 
38
38
  ## Library
39
39
 
package/README.md CHANGED
@@ -23,8 +23,7 @@ Mail client library for the Eliware mail platform.
23
23
 
24
24
  ## Features
25
25
 
26
- Call the mail-server HTTP API and receive WebSocket events from Node.js and browser applications.
27
- Provide bearer tokens through the host application and keep API responses available to callers.
26
+ Call the mail-server API from Node.js and browser applications. Receive WebSocket events and preserve server response envelopes.
28
27
 
29
28
  ## Requirements
30
29
 
@@ -32,38 +31,27 @@ Use Node.js 26 or later. Browser applications require Fetch, Headers, AbortSigna
32
31
 
33
32
  ## Setup
34
33
 
35
- After the npm release, install the package with `npm install @eliware/mail-client`.
36
- Set the mail API URL and a bearer-token provider in the host application.
37
- Read the [usage guide](docs/usage.md) for configuration details.
34
+ Install the package with `npm install @eliware/mail-client`. Follow the [usage guide](docs/usage.md) to configure the API address and bearer-token provider.
38
35
 
39
36
  ## Usage
40
37
 
41
- Read the [usage guide](docs/usage.md) and [release notes](RELEASE_NOTES.md).
42
- The [basic example](examples/README.md) requests mail API status.
38
+ Follow the [usage guide](docs/usage.md). Find client methods in the [API reference](docs/api.md) and version changes in the [release notes](RELEASE_NOTES.md).
43
39
 
44
40
  ## Development
45
41
 
46
- Read [AGENTS.md](AGENTS.md) before changing files.
47
- Read the [documentation index](docs/README.md) and [specifications index](specs/README.md) for package guidance.
48
- Run `npm ci` to install locked dependencies.
42
+ Read [AGENTS.md](AGENTS.md) and [specifications](specs/README.md) before changing files. Find maintained guides in [documentation](docs/README.md).
49
43
 
50
44
  ## Testing
51
45
 
52
- Run `npm test` for aggregate checks.
53
- Run `npm run smoke` for a local HTTP and WebSocket check.
54
- Run `npm run typecheck` to check TypeScript declarations.
55
- Run `npm run pack` to check package contents.
46
+ Run `npm test` for aggregate validation. Run `npm run smoke` to check an HTTP and WebSocket connection.
56
47
 
57
48
  ## Troubleshooting
58
49
 
59
- Check the API URL, bearer-token provider, and network access when a request fails.
60
- Read the [API reference](docs/api.md) for errors and response details.
50
+ Read the [troubleshooting guide](docs/troubleshooting.md) for common API and connection problems.
61
51
 
62
52
  ## Security
63
53
 
64
- Keep API keys and temporary credentials in approved secret stores.
65
- Do not log bearer tokens.
66
- Do not expose static API keys to browser code.
54
+ Keep long-lived API tokens in server-side secret stores. Do not expose them to browser code or logs.
67
55
 
68
56
  ## API
69
57
 
@@ -71,9 +59,7 @@ Read the [API reference](docs/api.md) for client options, methods, events, loggi
71
59
 
72
60
  ## Packaging
73
61
 
74
- Use the npm publication workflow with provenance.
75
- Use version tags that match `package.json`.
76
- Follow approved release steps before you publish a tag.
62
+ Read [package details](docs/package.md) for runtime support, package contents, and version rules. Read [release notes](RELEASE_NOTES.md) for package changes.
77
63
 
78
64
  ## Examples
79
65
 
package/RELEASE_NOTES.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Release Notes
2
2
 
3
+ ## 15.0.3 — 2026-10-30
4
+
5
+ ### Added
6
+
7
+ - Add a package guide for runtime support, entrypoints, environment values, package contents, and publication.
8
+
9
+ ### Changed
10
+
11
+ - Set the package version to 15.0.3.
12
+ - Send `consumer_id` in durable WebSocket requests and use the server-stored consumer cursor.
13
+ - Reject `after` when a WebSocket connection uses `consumerId`.
14
+ - Keep `ready` pending while automatic reconnect retries token-provider or socket failures.
15
+ - Update locked transitive dependencies and simplify README navigation.
16
+
17
+ ### Fixed
18
+
19
+ - Stop queued event handlers after an earlier event handler fails.
20
+ - Reject browser WebSocket frames that contain binary `Blob` data.
21
+
22
+ ## 15.0.2 — 2026-10-30
23
+
24
+ ### Added
25
+
26
+ - Add timestamped JSON logs through `@eliware/log` for HTTP and WebSocket requests.
27
+ - Add debug-level lifecycle records controlled by `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
28
+ - Add an end-user troubleshooting guide for authentication, browser access, WebSocket events, and logs.
29
+
30
+ ### Changed
31
+
32
+ - Set the package version to 15.0.2.
33
+ - Replace the direct `@eliware/common` dependency with `@eliware/log`.
34
+ - Update locked dependencies and align the README and contributor guidance with repository conventions.
35
+ - Resolve request paths that start with `//` on the configured API address.
36
+ - Keep browser logging silent by default and allow injected loggers for HTTP and WebSocket calls.
37
+
38
+ ### Fixed
39
+
40
+ - Resolve the WebSocket readiness promise when event processing fails.
41
+
3
42
  ## 15.0.1 — 2026-10-29
4
43
 
5
44
  ### Added
package/docs/README.md CHANGED
@@ -6,3 +6,5 @@ This directory contains user and API documentation for `@eliware/mail-client`.
6
6
 
7
7
  - [Usage](usage.md)
8
8
  - [API reference](api.md)
9
+ - [Package details](package.md)
10
+ - [Troubleshooting](troubleshooting.md)
package/docs/api.md CHANGED
@@ -15,7 +15,7 @@ Call `createMailClient(options)` to create an HTTP and WebSocket client.
15
15
  | `timeoutMs` | No | `15000` | Sets the timeout for each HTTP request. |
16
16
  | `logger` | No | Node.js: `@eliware/log`, browser: silent | Supplies `debug`, `warn`, and `error` methods. |
17
17
 
18
- Use an HTTP or HTTPS base address without a path, query, fragment, user name, or password. The client rejects request paths that resolve to a different address.
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
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.
21
21
 
@@ -141,7 +141,7 @@ The error message uses the API error message when available. Network errors and
141
141
 
142
142
  ### `connectEvents(options)`
143
143
 
144
- Open the `/ws` route and receive event notifications. The WebSocket URL uses `ws` for an HTTP base address and `wss` for an HTTPS base address. The client puts the optional `after` cursor in the URL and excludes tokens.
144
+ Open the `/ws` route and receive event notifications. The WebSocket URL uses `ws` for an HTTP base address and `wss` for an HTTPS base address. The client puts the optional `after` cursor or `consumer_id` in the URL and excludes tokens.
145
145
 
146
146
  After the socket opens, the client sends this JSON frame as its first message:
147
147
 
@@ -155,22 +155,25 @@ The client waits for this server frame before it delivers events:
155
155
  { "type": "authenticated" }
156
156
  ```
157
157
 
158
- | Option | Default | Description |
159
- | --------------------- | ------------- | --------------------------------------------------------------------------- |
160
- | `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
161
- | `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
162
- | `after` | Live edge | Starts event replay after a decimal cursor. |
163
- | `consumerId` | None | Enables server-side cursor acknowledgements. |
164
- | `autoReconnect` | `true` | Reconnects after unexpected closure. |
165
- | `retryDelayMs` | `500` | Sets the first reconnect wait interval. |
166
- | `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
167
- | `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
158
+ | Option | Default | Description |
159
+ | --------------------- | ------------- | ------------------------------------------------------------------------------ |
160
+ | `onEvent(event)` | Required | Processes one JSON event. A returned promise delays cursor acknowledgement. |
161
+ | `onError(error)` | No operation | Receives socket, handler, and acknowledgement errors. |
162
+ | `logger` | Client logger | Overrides the logger for this event connection. |
163
+ | `after` | Live edge | Starts event replay after a decimal cursor. |
164
+ | `consumerId` | None | Sends `consumer_id` to the server and enables durable cursor acknowledgements. |
165
+ | `autoReconnect` | `true` | Reconnects after unexpected closure. |
166
+ | `retryDelayMs` | `500` | Sets the first reconnect wait interval. |
167
+ | `maxReconnectDelayMs` | `30000` | Sets the longest reconnect wait interval. |
168
+ | `WebSocketImpl` | Client option | Overrides the WebSocket constructor for this connection. |
168
169
 
169
- The connection object exposes `ready`, `cursor`, and `close()`. The `ready` promise resolves after the first authentication acknowledgement. It rejects if the first token request fails or the socket closes before authentication. A rejected token request retries automatically when `autoReconnect` is enabled. An invalid token value or WebSocket construction error stops automatic reconnects.
170
+ The connection object exposes `ready`, `cursor`, and `close()`. 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. The promise rejects when retries stop before authentication, the token value is invalid, socket construction fails, or the caller closes the connection.
170
171
 
171
172
  The server accepts cursors from `0` through the maximum Snowflake ID. It requires decimal strings without leading zeroes, except for `0` itself.
172
173
 
173
- The client calls one event handler at a time. With `consumerId`, it acknowledges an event after its handler succeeds. It advances `cursor` only after the server accepts that acknowledgement. If event handling or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
174
+ The client calls one event handler at a time. With `consumerId`, it sends that ID in the WebSocket URL and acknowledges each event after its handler succeeds. The server stores progress for that consumer. The client advances `cursor` only after the server accepts the acknowledgement. If event handling or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
175
+
176
+ Do not pass both `after` and `consumerId`. The server uses `after` for cursor-based replay and `consumer_id` for durable replay. The server rejects a request that includes both values.
174
177
 
175
178
  Without `consumerId`, `cursor` remains in memory and is used when the connection reconnects. Store the cursor outside the client if it must survive a new process start. Make event handlers safe to run more than once.
176
179
 
@@ -178,6 +181,6 @@ The event has `event_id`, `cursor`, `event_type`, `occurred_at`, and `payload` f
178
181
 
179
182
  ## Runtime logging
180
183
 
181
- The Node.js entry uses `@eliware/log` by default. 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.
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.
182
185
 
183
- The client logs HTTP methods, response statuses, error names, and request IDs. It does not log bearer tokens, message bodies, attachment bytes, or full request addresses.
186
+ 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.
@@ -0,0 +1,47 @@
1
+ # Package details
2
+
3
+ ## Installation and support
4
+
5
+ Install the package with npm:
6
+
7
+ ```sh
8
+ npm install @eliware/mail-client
9
+ ```
10
+
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
+
13
+ The package root exports `createMailClient` and `MailApiError`. 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
+
15
+ The Node.js entry uses `@eliware/log` as a runtime dependency. The browser entry does not import the Node.js logger. Both entries expose the same client API.
16
+
17
+ ## Environment values
18
+
19
+ The library accepts `baseUrl` and `getAccessToken` as required client options. It does not read API URLs or API tokens from the environment. The examples use these application-owned values:
20
+
21
+ | Value | Example default | Required status | Purpose |
22
+ | ----------------------- | ---------------------------- | -------------------------------- | -------------------------------------------------------- |
23
+ | `MAIL_API_URL` | `https://mail.example.test` | Required by usage examples | Sets the mail-server base address. |
24
+ | `MAIL_API_TOKEN` | `replace-with-a-local-token` | Required by the Node.js examples | Supplies a bearer token to the example host. |
25
+ | `MAIL_WEB_API_TOKEN` | None | Required by the mail-web example | Supplies the server token for browser-token requests. |
26
+ | `MAIL_CLIENT_LOG_LEVEL` | `LOG_LEVEL` or `info` | Optional for the Node.js entry | Sets the package logger level. |
27
+ | `LOG_LEVEL` | `info` | Optional for the Node.js entry | Sets the logger level when the package value is missing. |
28
+
29
+ The host application reads the first three values and passes them to the library. Keep long-lived tokens on trusted servers. The library reads the two log-level values in the Node.js entry. The browser entry does not read them.
30
+
31
+ The package requires `baseUrl` and `getAccessToken` when you create a client. The environment values above belong to the example host applications. Only the two log-level values come from the library process environment.
32
+
33
+ ## Package contents
34
+
35
+ The npm package includes `src/`, `docs/`, `examples/`, `specs/`, `README.md`, `AGENTS.md`, `LICENSE`, `RELEASE_NOTES.md`, and `package.json`. These paths contain runtime entries, declarations, user guides, examples, and package metadata.
36
+
37
+ The package does not include tests, fixtures, coverage output, or the lockfile. npm installs the runtime dependency declared in `package.json`.
38
+
39
+ ## Versions and publication
40
+
41
+ The package uses numeric `MAJOR.MINOR.PATCH` versions. Each release tag follows `vMAJOR.MINOR.PATCH` and matches `package.json`.
42
+
43
+ The GitHub publication workflow tests each tagged commit with Node.js 26 before it publishes the package. It runs `npm test`.
44
+
45
+ npm adds provenance data that identifies the GitHub Actions build that published the package. The package is public on npm under `@eliware/mail-client`.
46
+
47
+ Read [release notes](../RELEASE_NOTES.md) for changes in each published version.
@@ -0,0 +1,33 @@
1
+ # Troubleshooting
2
+
3
+ Use this guide to find common mail-server API and WebSocket connection problems.
4
+
5
+ ## HTTP authentication fails
6
+
7
+ Check that the token provider returns a valid bearer token for every request. Mail-client calls the provider before each HTTP request.
8
+
9
+ For browser requests, request a new short-lived token through the signed-in host application. Keep long-lived API tokens on the server.
10
+
11
+ Read the `MailApiError` status, code, and request ID. Use the request ID to find the matching mail-server log record.
12
+
13
+ ## Browser requests fail
14
+
15
+ Check that mail-server allows the exact browser site address. Include the scheme and port from the browser address.
16
+
17
+ Allow the browser site address for both HTTP and WebSocket access. Check the browser network panel for CORS details.
18
+
19
+ ## WebSocket events are missing
20
+
21
+ Wait for `connection.ready` before treating the connection as authenticated. The server must send `{"type":"authenticated"}` before it sends events.
22
+
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
+
25
+ Check the `onError` callback for socket, event handler, or acknowledgement failures. Event handlers must succeed before mail-client acknowledges their cursor.
26
+
27
+ ## Debug logs are missing
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.
30
+
31
+ The browser entry stays silent by default. Pass a logger with `debug`, `warn`, and `error` methods to receive browser-side records.
32
+
33
+ Mail-client omits tokens, message bodies, attachment bytes, event payloads, and complete request addresses from its own records.
package/docs/usage.md CHANGED
@@ -18,6 +18,8 @@ Use a long-lived API token in trusted Node.js applications. Keep a different tok
18
18
 
19
19
  Use a short-lived browser token in browser code. The mail-web server keeps its long-lived token and requests a browser token from `POST /api/auth/token`. The mail-web server sends the short-lived token to the signed-in browser through its authenticated session.
20
20
 
21
+ The library does not read `MAIL_API_URL`, `MAIL_API_TOKEN`, or `MAIL_WEB_API_TOKEN`. The host application reads those values and passes them through `baseUrl` and `getAccessToken`. Read [package details](package.md) for each value's purpose and default.
22
+
21
23
  EliD sign-in belongs to mail-web. This package does not run OAuth flows and does not depend on `@eliware/elid-client`.
22
24
 
23
25
  ## Create a Node.js client
@@ -113,24 +115,25 @@ const events = browserMail.connectEvents({
113
115
  await events.ready;
114
116
  ```
115
117
 
116
- The server sends `{"type":"authenticated"}` before it sends events. The client resolves `ready` after it receives that frame. The client rejects `ready` if the first connection closes before authentication succeeds.
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.
117
119
 
118
120
  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.
119
121
 
120
122
  ## Process durable events
121
123
 
122
- Use a stable `consumerId` when the application must store progress on mail-server. Set `after` to a saved decimal cursor when processing must start from an earlier event.
124
+ Use a stable `consumerId` when the application must store progress on mail-server. The client sends it as `consumer_id` when it opens the WebSocket. The server resumes from the saved cursor for that consumer.
123
125
 
124
126
  ```js
125
127
  const events = browserMail.connectEvents({
126
128
  consumerId: "mail-discord-production",
127
- after: savedCursor,
128
129
  onEvent: handleEvent,
129
130
  onError: reportEventError,
130
131
  });
131
132
  ```
132
133
 
133
- The client runs one event handler at a time. After a handler succeeds, the client posts its cursor to the acknowledgement route. The client advances its cursor only after that request succeeds. If a handler or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
134
+ The client runs one event handler at a time. After a handler succeeds, the client posts its cursor to the acknowledgement route with the same consumer ID. The client advances its cursor only after that request succeeds. If a handler or acknowledgement fails, the client reports the error, closes the socket, and stops automatic reconnects.
135
+
136
+ Do not set `after` when you set `consumerId`. The server uses the durable consumer cursor for replay and rejects requests that include both values.
134
137
 
135
138
  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.
136
139
 
@@ -146,7 +149,7 @@ Use `onError` for WebSocket, event-handler, and event-acknowledgement failures.
146
149
 
147
150
  ## Configure logging
148
151
 
149
- The Node.js entry uses `@eliware/log` by default. Pass a logger with `debug`, `warn`, and `error` methods to use the host logger.
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.
150
153
 
151
154
  ```js
152
155
  const mail = createMailClient({
@@ -156,7 +159,7 @@ const mail = createMailClient({
156
159
  });
157
160
  ```
158
161
 
159
- The browser entry has a silent logger by default and imports no Node-only logger. The client logs HTTP methods, response statuses, error names, and request IDs. It does not log tokens, message bodies, attachment bytes, or full request addresses.
162
+ The browser entry has a silent logger by default and imports no Node-only logger. The client logs HTTP methods, response statuses, durations, error names, request IDs, and WebSocket lifecycle details. It does not log tokens, message bodies, attachment bytes, event payloads, or full request addresses.
160
163
 
161
164
  ## Validate a checkout
162
165
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eliware/mail-client",
3
- "version": "15.0.1",
3
+ "version": "15.0.3",
4
4
  "type": "module",
5
5
  "description": "Mail client library for the Eliware mail platform.",
6
6
  "keywords": [
@@ -41,7 +41,7 @@
41
41
  "node": ">=26"
42
42
  },
43
43
  "dependencies": {
44
- "@eliware/log": "^15.0.0"
44
+ "@eliware/log": "^15.0.1"
45
45
  },
46
46
  "devDependencies": {
47
47
  "@eliware/test": "^15.0.1",
@@ -57,6 +57,8 @@ directives:
57
57
  - Reconnect safely and continue events from the last acknowledged cursor.
58
58
  - Retry WebSocket setup after token provider failures when automatic reconnect is enabled.
59
59
  - Let stable consumer IDs acknowledge processed event cursors through the HTTP API.
60
+ - Send a stable consumer ID as `consumer_id` when opening a durable WebSocket connection.
61
+ - Use the server-stored consumer cursor for durable WebSocket event replay.
60
62
  - Move durable cursors only after handlers and server acknowledgements succeed.
61
63
  - Tolerate repeated events and refresh current data through the HTTP API after notifications.
62
64
  - Let callers process events without RabbitMQ payloads as a client contract.
@@ -67,10 +69,13 @@ directives:
67
69
 
68
70
  - id: E-1361.4
69
71
  dos:
70
- - Use `@eliware/log` for structured logs in the Node.js package entry.
71
- - Accept an injected logger with `debug`, `warn`, and `error` methods.
72
+ - Use `@eliware/log` directly for timestamped JSON logs in the Node.js package entry.
73
+ - Set the default log level through `MAIL_CLIENT_LOG_LEVEL` or `LOG_LEVEL`.
74
+ - Accept an injected logger with `debug`, `warn`, and `error` methods for HTTP and WebSocket
75
+ events.
72
76
  - Omit Node-only logging imports from the browser entry.
73
77
  - Log request methods, response statuses, error names, and available request IDs.
74
78
  donts:
75
- - Do not log tokens, message bodies, attachment contents, or full request URLs.
79
+ - Do not log tokens, message bodies, attachment contents, event payloads, or full request
80
+ URLs.
76
81
  - Do not require logging from browser clients.
package/src/index.d.ts CHANGED
@@ -43,6 +43,7 @@ export interface EventConnectionOptions {
43
43
  retryDelayMs?: number;
44
44
  maxReconnectDelayMs?: number;
45
45
  WebSocketImpl?: WebSocketFactory;
46
+ logger?: MailLogger;
46
47
  }
47
48
 
48
49
  export interface EventConnection {
package/src/index.mjs CHANGED
@@ -1,6 +1,13 @@
1
- import defaultLogger from "@eliware/log";
1
+ import { createLogger } from "@eliware/log";
2
2
  import { createMailClient as createClient } from "./mail/client.mjs";
3
3
 
4
+ const defaultLogger = createLogger({
5
+ level: process.env.MAIL_CLIENT_LOG_LEVEL ?? process.env.LOG_LEVEL ?? "info",
6
+ format: "json",
7
+ timestamp: true,
8
+ keys: ["token", "access_token", "authorization", "body", "payload", "attachments"],
9
+ });
10
+
4
11
  export function createMailClient(options) {
5
12
  return createClient({ ...options, logger: options?.logger ?? defaultLogger });
6
13
  }
@@ -1,5 +1,5 @@
1
1
  import { createApiMethods } from "./api/methods.mjs";
2
- import { createEventConnection } from "./event-connection.mjs";
2
+ import { createEventConnection } from "./event/connection.mjs";
3
3
  import { createTransport } from "./transport.mjs";
4
4
 
5
5
  export function createMailClient(options = {}) {
@@ -15,6 +15,7 @@ export function createMailClient(options = {}) {
15
15
  getAccessToken: options.getAccessToken,
16
16
  WebSocketImpl: settings.WebSocketImpl ?? options.WebSocketImpl,
17
17
  acknowledgeEvent: api.events.acknowledge,
18
+ logger: settings.logger ?? options.logger,
18
19
  });
19
20
  },
20
21
  };
@@ -0,0 +1,71 @@
1
+ const noop = () => {};
2
+ const silentLogger = { debug: noop, warn: noop, error: noop };
3
+
4
+ function errorName(error) {
5
+ return typeof error?.name === "string" ? error.name : "Error";
6
+ }
7
+
8
+ export function createEventConnectionLogger(logger = silentLogger) {
9
+ function write(level, message, metadata) {
10
+ try {
11
+ logger[level](message, metadata);
12
+ } catch {}
13
+ }
14
+
15
+ return {
16
+ started(cursor) {
17
+ write("debug", "Mail event connection started", { cursor });
18
+ },
19
+ tokenProviderFailed(error) {
20
+ write("error", "Mail event token provider failed", { errorName: errorName(error) });
21
+ },
22
+ invalidToken() {
23
+ write("error", "Mail event token provider returned an invalid token", {
24
+ errorName: "TypeError",
25
+ });
26
+ },
27
+ reconnectScheduled(closeCode, delay, attempt, cursor) {
28
+ write("warn", "Mail event connection reconnect scheduled", {
29
+ closeCode,
30
+ delayMs: delay,
31
+ attempt,
32
+ cursor,
33
+ });
34
+ },
35
+ eventSkipped(cursor) {
36
+ write("debug", "Mail event skipped because its cursor was already handled", { cursor });
37
+ },
38
+ eventStarted(eventType, cursor) {
39
+ write("debug", "Mail event handling started", { eventType, cursor });
40
+ },
41
+ eventCompleted(eventType, cursor, acknowledged) {
42
+ write("debug", "Mail event handling completed", { eventType, cursor, acknowledged });
43
+ },
44
+ authenticated(cursor) {
45
+ write("debug", "Mail event connection authenticated", { cursor });
46
+ },
47
+ eventFailed(event, error) {
48
+ write("error", "Mail event handling failed", {
49
+ eventType: event?.event_type,
50
+ cursor: event?.cursor ?? event?.event_id,
51
+ errorName: errorName(error),
52
+ });
53
+ },
54
+ closed(closeCode, authenticated, cursor) {
55
+ write(authenticated ? "debug" : "warn", "Mail event connection closed", {
56
+ closeCode,
57
+ authenticated,
58
+ cursor,
59
+ });
60
+ },
61
+ socketFailed(error) {
62
+ write("error", "Mail event socket failed", { errorName: errorName(error) });
63
+ },
64
+ startFailed(error) {
65
+ write("error", "Mail event connection failed to start", { errorName: errorName(error) });
66
+ },
67
+ clientClosed(cursor) {
68
+ write("debug", "Mail event connection closed by client", { cursor });
69
+ },
70
+ };
71
+ }
@@ -1,9 +1,9 @@
1
- import { createWebSocketSession } from "./websocket/session.mjs";
2
- import { socketUrl } from "./websocket/address.mjs";
3
- import { isValidCursor } from "./websocket/cursor.mjs";
4
- import { validateEventOptions } from "./websocket/options.mjs";
5
-
6
- const noop = () => {};
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
7
 
8
8
  export function createEventConnection({
9
9
  baseUrl,
@@ -13,38 +13,33 @@ export function createEventConnection({
13
13
  after,
14
14
  consumerId,
15
15
  onEvent,
16
- onError = noop,
16
+ onError = () => {},
17
17
  autoReconnect = true,
18
18
  retryDelayMs = 500,
19
19
  maxReconnectDelayMs = 30_000,
20
+ logger,
20
21
  } = {}) {
21
- const options = {
22
+ const logs = createEventConnectionLogger(logger);
23
+ validateEventOptions({
22
24
  getAccessToken,
23
25
  WebSocketImpl,
24
26
  onEvent,
25
27
  onError,
26
28
  consumerId,
27
29
  acknowledgeEvent,
30
+ logger,
28
31
  retryDelayMs,
29
32
  maxReconnectDelayMs,
30
33
  after,
31
- };
32
- validateEventOptions(options);
34
+ });
33
35
  let cursor = after ?? null;
34
36
  let socket;
35
37
  let timer;
36
38
  let stopped = false;
37
39
  let attempt = 0;
38
40
  let authenticated = false;
39
- let initialSettled = false;
40
41
  let processing = Promise.resolve();
41
- let resolveReady;
42
- let rejectReady;
43
- const ready = new Promise((resolve, reject) => {
44
- resolveReady = resolve;
45
- rejectReady = reject;
46
- });
47
- void ready.catch(noop);
42
+ const { ready, settle: settleReady } = createReadyState();
48
43
 
49
44
  function report(error) {
50
45
  try {
@@ -52,81 +47,87 @@ export function createEventConnection({
52
47
  } catch {}
53
48
  }
54
49
 
55
- function settleReady(error) {
56
- if (initialSettled) return;
57
- initialSettled = true;
58
- if (error) rejectReady(error);
59
- else resolveReady();
60
- }
61
-
62
50
  function scheduleReconnect(code) {
63
- if (stopped || !autoReconnect || code === 1000 || code === 1008) return;
51
+ if (stopped || !autoReconnect || code === 1000 || code === 1008) return false;
64
52
  const delay = Math.min(retryDelayMs * 2 ** attempt, maxReconnectDelayMs);
65
53
  attempt += 1;
54
+ logs.reconnectScheduled(code, delay, attempt, cursor);
66
55
  timer = setTimeout(connect, delay);
67
56
  timer.unref?.();
57
+ return true;
68
58
  }
69
59
 
70
- async function processEvent(event) {
71
- const eventCursor = event.cursor ?? event.event_id;
72
- if (!isValidCursor(eventCursor)) {
73
- throw new TypeError("event cursor must be a decimal Snowflake cursor");
74
- }
75
- if (cursor !== null && BigInt(eventCursor) <= BigInt(cursor)) return;
76
- await onEvent(event);
77
- if (consumerId !== undefined) await acknowledgeEvent(consumerId, eventCursor);
78
- cursor = eventCursor;
79
- }
60
+ const processEvent = createEventProcessor({
61
+ getCursor: () => cursor,
62
+ setCursor: (value) => {
63
+ cursor = value;
64
+ },
65
+ consumerId,
66
+ acknowledgeEvent,
67
+ onEvent,
68
+ logs,
69
+ });
80
70
 
81
71
  async function connect() {
82
72
  if (stopped) return;
83
73
  authenticated = false;
74
+ logs.started(cursor);
84
75
  let token;
85
76
  try {
86
77
  token = await getAccessToken();
87
78
  } catch (error) {
88
79
  if (stopped) return;
80
+ logs.tokenProviderFailed(error);
89
81
  report(error);
90
- settleReady(error);
91
- scheduleReconnect(1006);
82
+ if (!scheduleReconnect(1006)) settleReady(error);
92
83
  return;
93
84
  }
94
85
  if (stopped) return;
95
86
  if (typeof token !== "string" || token.length === 0) {
96
87
  const error = new TypeError("getAccessToken must return a non-empty bearer token");
97
88
  stopped = true;
89
+ logs.invalidToken();
98
90
  report(error);
99
91
  settleReady(error);
100
92
  return;
101
93
  }
102
94
  try {
103
95
  socket = createWebSocketSession({
104
- url: socketUrl(baseUrl, cursor),
96
+ url: socketUrl(baseUrl, consumerId === undefined ? cursor : null, consumerId),
105
97
  token,
106
98
  WebSocketImpl,
107
99
  onAuthenticated: () => {
108
100
  authenticated = true;
109
101
  attempt = 0;
102
+ logs.authenticated(cursor);
110
103
  settleReady();
111
104
  },
112
105
  onEvent: (event) => {
113
106
  processing = processing
114
- .then(() => processEvent(event))
107
+ .then(() => (stopped ? undefined : processEvent(event)))
115
108
  .catch((error) => {
109
+ logs.eventFailed(event, error);
116
110
  report(error);
117
111
  stopped = true;
112
+ settleReady(error);
118
113
  socket.close(1011, "event processing failed");
119
114
  });
120
115
  },
121
116
  onClose: (code) => {
122
- if (!authenticated)
117
+ logs.closed(code, authenticated, cursor);
118
+ const reconnecting = scheduleReconnect(code);
119
+ if (!authenticated && !reconnecting) {
123
120
  settleReady(new Error(`WebSocket authentication closed with code ${code}`));
124
- scheduleReconnect(code);
121
+ }
122
+ },
123
+ onError: (error) => {
124
+ logs.socketFailed(error);
125
+ report(error);
125
126
  },
126
- onError: report,
127
127
  });
128
128
  } catch (error) {
129
129
  stopped = true;
130
+ logs.startFailed(error);
130
131
  report(error);
131
132
  settleReady(error);
132
133
  }
@@ -141,6 +142,7 @@ export function createEventConnection({
141
142
  close() {
142
143
  stopped = true;
143
144
  if (timer) clearTimeout(timer);
145
+ logs.clientClosed(cursor);
144
146
  settleReady(new Error("WebSocket connection closed by the client"));
145
147
  socket?.close(1000, "client closed");
146
148
  },
@@ -0,0 +1,27 @@
1
+ import { isValidCursor } from "../websocket/cursor.mjs";
2
+
3
+ export function createEventProcessor({
4
+ getCursor,
5
+ setCursor,
6
+ consumerId,
7
+ acknowledgeEvent,
8
+ onEvent,
9
+ logs,
10
+ }) {
11
+ return async function processEvent(event) {
12
+ const eventCursor = event.cursor ?? event.event_id;
13
+ if (!isValidCursor(eventCursor)) {
14
+ throw new TypeError("event cursor must be a decimal Snowflake cursor");
15
+ }
16
+ const cursor = getCursor();
17
+ if (cursor !== null && BigInt(eventCursor) <= BigInt(cursor)) {
18
+ logs.eventSkipped(eventCursor);
19
+ return;
20
+ }
21
+ logs.eventStarted(event?.event_type, eventCursor);
22
+ await onEvent(event);
23
+ if (consumerId !== undefined) await acknowledgeEvent(consumerId, eventCursor);
24
+ setCursor(eventCursor);
25
+ logs.eventCompleted(event?.event_type, eventCursor, consumerId !== undefined);
26
+ };
27
+ }
@@ -0,0 +1,19 @@
1
+ export function createReadyState() {
2
+ let settled = false;
3
+ let resolveReady;
4
+ let rejectReady;
5
+ const ready = new Promise((resolve, reject) => {
6
+ resolveReady = resolve;
7
+ rejectReady = reject;
8
+ });
9
+ void ready.catch(() => {});
10
+
11
+ function settle(error) {
12
+ if (settled) return;
13
+ settled = true;
14
+ if (error) rejectReady(error);
15
+ else resolveReady();
16
+ }
17
+
18
+ return { ready, settle };
19
+ }
@@ -50,11 +50,29 @@ export function createTransport({
50
50
  if (typeof path !== "string" || path.length === 0) {
51
51
  throw new TypeError("path must be a non-empty string");
52
52
  }
53
- const url = new URL(path, `${apiOrigin}/`);
53
+ const requestPath = path.startsWith("//") ? path.replace(/^\/+/, "/") : path;
54
+ const url = new URL(requestPath, `${apiOrigin}/`);
54
55
  if (url.origin !== apiOrigin) throw new TypeError("path must use the configured API origin");
55
56
 
56
- const token = await getAccessToken();
57
+ const method = String(options.method ?? "GET").toUpperCase();
58
+ const startedAt = Date.now();
59
+ logger.debug("Mail API request started", { method });
60
+ let token;
61
+ try {
62
+ token = await getAccessToken();
63
+ } catch (error) {
64
+ logger.error("Mail API access token provider failed", {
65
+ method,
66
+ durationMs: Date.now() - startedAt,
67
+ errorName: typeof error?.name === "string" ? error.name : "Error",
68
+ });
69
+ throw error;
70
+ }
57
71
  if (typeof token !== "string" || token.length === 0) {
72
+ logger.error("Mail API access token provider returned an invalid token", {
73
+ method,
74
+ durationMs: Date.now() - startedAt,
75
+ });
58
76
  throw new TypeError("getAccessToken must return a non-empty bearer token");
59
77
  }
60
78
 
@@ -72,12 +90,15 @@ export function createTransport({
72
90
  const signal = options.signal
73
91
  ? AbortSignal.any([options.signal, timeoutSignal])
74
92
  : timeoutSignal;
75
- const method = String(options.method ?? "GET").toUpperCase();
76
93
  let response;
77
94
  try {
78
95
  response = await fetchImpl(url, { ...options, method, headers, body: requestBody, signal });
79
96
  } catch (error) {
80
- logger.error("Mail API request failed", { method, errorName: error?.name ?? "Error" });
97
+ logger.error("Mail API request failed", {
98
+ method,
99
+ durationMs: Date.now() - startedAt,
100
+ errorName: typeof error?.name === "string" ? error.name : "Error",
101
+ });
81
102
  throw error;
82
103
  }
83
104
  if (!response.ok) {
@@ -89,6 +110,7 @@ export function createTransport({
89
110
  logger.warn("Mail API request failed", {
90
111
  method,
91
112
  status: error.status,
113
+ durationMs: Date.now() - startedAt,
92
114
  code: error.code,
93
115
  requestId: error.requestId,
94
116
  });
@@ -97,6 +119,7 @@ export function createTransport({
97
119
  logger.debug("Mail API request completed", {
98
120
  method,
99
121
  status: response.status,
122
+ durationMs: Date.now() - startedAt,
100
123
  requestId: response.headers.get("x-request-id"),
101
124
  });
102
125
  return response;
@@ -1,6 +1,7 @@
1
- export function socketUrl(baseUrl, cursor) {
1
+ export 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
+ if (consumerId !== undefined) url.searchParams.set("consumer_id", consumerId);
5
6
  return url.toString();
6
7
  }
@@ -7,6 +7,7 @@ export function validateEventOptions({
7
7
  onError,
8
8
  consumerId,
9
9
  acknowledgeEvent,
10
+ logger,
10
11
  retryDelayMs,
11
12
  maxReconnectDelayMs,
12
13
  after,
@@ -17,6 +18,14 @@ export function validateEventOptions({
17
18
  throw new TypeError("WebSocketImpl must be a constructor");
18
19
  if (typeof onEvent !== "function") throw new TypeError("onEvent must be a function");
19
20
  if (typeof onError !== "function") throw new TypeError("onError must be a function");
21
+ if (
22
+ logger !== undefined &&
23
+ (typeof logger?.debug !== "function" ||
24
+ typeof logger?.warn !== "function" ||
25
+ typeof logger?.error !== "function")
26
+ ) {
27
+ throw new TypeError("logger must provide debug, warn, and error methods");
28
+ }
20
29
  if (consumerId !== undefined && (typeof consumerId !== "string" || consumerId.length === 0)) {
21
30
  throw new TypeError("consumerId must be a non-empty string");
22
31
  }
@@ -32,4 +41,7 @@ export function validateEventOptions({
32
41
  if (after !== undefined && !isValidCursor(after)) {
33
42
  throw new TypeError("after must be a decimal Snowflake cursor");
34
43
  }
44
+ if (after !== undefined && consumerId !== undefined) {
45
+ throw new TypeError("after and consumerId cannot be used together");
46
+ }
35
47
  }
@@ -16,7 +16,8 @@ export function createWebSocketSession({
16
16
  socket.send(JSON.stringify({ type: "authenticate", token }));
17
17
  });
18
18
  subscribe(socket, "message", (value, isBinary = false) => {
19
- if (isBinary) {
19
+ const data = value?.data;
20
+ if (isBinary || (typeof Blob !== "undefined" && data instanceof Blob)) {
20
21
  onError(new TypeError("WebSocket frames must use JSON text"));
21
22
  socket.close(1002, "JSON text required");
22
23
  return;