@postalsys/ee-client 1.3.2 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +162 -113
- package/index.d.ts +45 -6
- package/index.js +176 -126
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
# @postalsys/ee-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Client library for [EmailEngine](https://emailengine.app/) that works in both the browser and Node.js.
|
|
4
|
+
|
|
5
|
+
It wraps the EmailEngine REST API (`/v1/account/...`) so you can list folders, read and search messages, change flags, move and delete messages, download attachments, and send mail. When you also give it a DOM element, it renders a complete, self-contained webmail interface (folder tree, paginated message list, message viewer, compose modal, dark mode) into that element.
|
|
6
|
+
|
|
7
|
+
This is the same client that powers the built-in message browser in the EmailEngine admin UI.
|
|
8
|
+
|
|
9
|
+
## About EmailEngine
|
|
10
|
+
|
|
11
|
+
[EmailEngine](https://emailengine.app/) is a headless email client application that exposes IMAP, SMTP, Gmail API, and Microsoft Graph API accounts through a single unified REST API and webhooks. This library talks to that REST API - you need a running EmailEngine instance to use it.
|
|
12
|
+
|
|
13
|
+
- Website: https://emailengine.app/
|
|
14
|
+
- API reference: https://api.emailengine.app/
|
|
15
|
+
- Documentation: https://docs.emailengine.app/
|
|
16
|
+
|
|
17
|
+
Note that EmailEngine (the server) is commercial software and requires a subscription; this client library is MIT-licensed.
|
|
4
18
|
|
|
5
19
|
## Installation
|
|
6
20
|
|
|
@@ -8,193 +22,228 @@ EmailEngine client library for browser and Node.js applications.
|
|
|
8
22
|
npm install @postalsys/ee-client
|
|
9
23
|
```
|
|
10
24
|
|
|
11
|
-
|
|
25
|
+
This package is **ES modules only** (`"type": "module"`). Import it with `import`; `require()` will not work.
|
|
12
26
|
|
|
13
|
-
|
|
14
|
-
npm install node-fetch
|
|
15
|
-
```
|
|
27
|
+
It has **no runtime dependencies** and uses the platform `fetch`:
|
|
16
28
|
|
|
17
|
-
|
|
29
|
+
- In the browser and on Node.js 18+, the global `fetch` is used automatically.
|
|
30
|
+
- On older Node.js (14-17), install [`node-fetch`](https://www.npmjs.com/package/node-fetch) as a fallback:
|
|
18
31
|
|
|
19
|
-
|
|
32
|
+
```bash
|
|
33
|
+
npm install node-fetch
|
|
34
|
+
```
|
|
20
35
|
|
|
21
|
-
|
|
22
|
-
import { EmailEngineClient } from '@postalsys/ee-client';
|
|
36
|
+
## Quick start
|
|
23
37
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
38
|
+
### Browser (embedded webmail UI)
|
|
39
|
+
|
|
40
|
+
Pass a `container` element and the client renders a full webmail UI into it and loads the inbox automatically:
|
|
41
|
+
|
|
42
|
+
```html
|
|
43
|
+
<div id="email-client" style="height: 600px;"></div>
|
|
44
|
+
<script type="module">
|
|
45
|
+
import { EmailEngineClient } from '@postalsys/ee-client';
|
|
46
|
+
|
|
47
|
+
const client = new EmailEngineClient({
|
|
48
|
+
apiUrl: 'https://your-emailengine-server.example.com',
|
|
49
|
+
account: 'your-account-id',
|
|
50
|
+
accessToken: 'your-access-token',
|
|
51
|
+
container: document.getElementById('email-client')
|
|
52
|
+
});
|
|
53
|
+
</script>
|
|
31
54
|
```
|
|
32
55
|
|
|
33
|
-
|
|
56
|
+
Because the browser talks to EmailEngine directly, use a short-lived, account-scoped token here (see [Authentication](#authentication)) - never a root or admin token.
|
|
57
|
+
|
|
58
|
+
### Node.js (API client, no UI)
|
|
59
|
+
|
|
60
|
+
Omit `container` to use the client purely as an API wrapper:
|
|
34
61
|
|
|
35
62
|
```javascript
|
|
36
63
|
import { EmailEngineClient } from '@postalsys/ee-client';
|
|
37
64
|
|
|
38
|
-
// Create client for API-only usage
|
|
39
65
|
const client = new EmailEngineClient({
|
|
40
|
-
apiUrl: 'https://your-emailengine-server.com',
|
|
66
|
+
apiUrl: 'https://your-emailengine-server.example.com',
|
|
41
67
|
account: 'your-account-id',
|
|
42
68
|
accessToken: 'your-access-token'
|
|
43
69
|
});
|
|
44
70
|
|
|
45
|
-
//
|
|
71
|
+
// List folders
|
|
46
72
|
const folders = await client.loadFolders();
|
|
47
73
|
|
|
48
74
|
// Load messages from INBOX
|
|
49
|
-
const { messages } = await client.loadMessages('INBOX');
|
|
75
|
+
const { messages, nextPageCursor } = await client.loadMessages('INBOX');
|
|
50
76
|
|
|
51
|
-
// Load a
|
|
77
|
+
// Load a single message (its HTML is returned pre-processed for safe display)
|
|
52
78
|
const message = await client.loadMessage(messages[0].id);
|
|
79
|
+
|
|
80
|
+
// Send a plain-text message
|
|
81
|
+
await client.sendMessage('user@example.com', 'Hello', 'Sent from ee-client');
|
|
82
|
+
|
|
83
|
+
// Release the keep-alive timer when done (see destroy() below)
|
|
84
|
+
client.destroy();
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
## Authentication
|
|
88
|
+
|
|
89
|
+
Every request is sent to EmailEngine with an `Authorization: Bearer <accessToken>` header. Tokens are scoped to a single account, so create one token per account you expose. There are two kinds of tokens you can pass as `accessToken`:
|
|
90
|
+
|
|
91
|
+
### Access tokens
|
|
92
|
+
|
|
93
|
+
Provision a long-lived, account-scoped access token with the `api` scope through the EmailEngine admin UI, or via the API:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
curl -XPOST "https://your-emailengine-server.example.com/v1/token" \
|
|
97
|
+
-H "Authorization: Bearer <root-token>" \
|
|
98
|
+
-H "Content-Type: application/json" \
|
|
99
|
+
-d '{
|
|
100
|
+
"account": "your-account-id",
|
|
101
|
+
"description": "Webmail client",
|
|
102
|
+
"scopes": ["api"]
|
|
103
|
+
}'
|
|
53
104
|
```
|
|
54
105
|
|
|
55
|
-
|
|
106
|
+
The response contains a `token` string to use as `accessToken`. Keep root tokens on your server; only hand an account-scoped `api` token to the browser.
|
|
107
|
+
|
|
108
|
+
### Session tokens (`sess_...`)
|
|
109
|
+
|
|
110
|
+
EmailEngine can also mint short-lived, session-bound tokens whose value starts with `sess_` (this is how its own built-in message browser is embedded). These expire quickly on inactivity. When the client detects a `sess_` token, it automatically pings `GET /v1/account/{account}` after about five minutes of inactivity to keep the token alive. Call [`destroy()`](#destroy-void) to stop that timer when you tear the client down.
|
|
111
|
+
|
|
112
|
+
## Constructor options
|
|
113
|
+
|
|
114
|
+
```javascript
|
|
115
|
+
new EmailEngineClient(options);
|
|
116
|
+
```
|
|
56
117
|
|
|
57
|
-
|
|
118
|
+
| Option | Type | Default | Description |
|
|
119
|
+
| --------------- | ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------- |
|
|
120
|
+
| `account` | `string` | (required) | EmailEngine account identifier. |
|
|
121
|
+
| `apiUrl` | `string` | `http://127.0.0.1:3000` | Base URL of your EmailEngine instance. |
|
|
122
|
+
| `accessToken` | `string` | - | Bearer token for API authentication. |
|
|
123
|
+
| `container` | `HTMLElement` | - | DOM element to render the webmail UI into. Omit for API-only use. |
|
|
124
|
+
| `pageSize` | `number` | `20` | Messages per page. A saved value in `localStorage` takes precedence. |
|
|
125
|
+
| `confirmMethod` | `function` | browser `confirm()` | Custom confirm dialog, `(message, title, cancelText, okText)`. May be sync or async; returns a boolean. |
|
|
126
|
+
| `alertMethod` | `function` | browser `alert()` | Custom alert dialog, `(message, title, cancelText, okText)` where `cancelText` is `null`. |
|
|
58
127
|
|
|
59
|
-
|
|
60
|
-
- `account` (string, required): Account identifier
|
|
61
|
-
- `accessToken` (string, optional): Access token for authentication
|
|
62
|
-
- `container` (HTMLElement, optional): DOM container for UI components (browser only)
|
|
63
|
-
- `confirmMethod` (function, optional): Custom confirm dialog method. Receives `(message, title, cancelText, okText)` parameters. Can be sync or async. Defaults to browser's `confirm()` with standard parameters.
|
|
64
|
-
- `alertMethod` (function, optional): Custom alert dialog method. Receives `(message, title, cancelText, okText)` parameters where `cancelText` is `null` for alerts. Can be sync or async. Defaults to browser's `alert()` with standard parameters.
|
|
128
|
+
UI rendering, the compose modal, and dark mode only activate when a `container` is supplied. In a non-browser environment the UI is skipped and the instance behaves as a plain API client.
|
|
65
129
|
|
|
66
|
-
|
|
130
|
+
### Factory helper
|
|
131
|
+
|
|
132
|
+
`createEmailEngineClient()` is a convenience wrapper that resolves a `containerId` to its DOM element and validates that `account` is present:
|
|
133
|
+
|
|
134
|
+
```javascript
|
|
135
|
+
import { createEmailEngineClient } from '@postalsys/ee-client';
|
|
136
|
+
|
|
137
|
+
// From an options object with a containerId
|
|
138
|
+
const client = createEmailEngineClient({
|
|
139
|
+
apiUrl: 'https://your-emailengine-server.example.com',
|
|
140
|
+
account: 'your-account-id',
|
|
141
|
+
accessToken: 'your-access-token',
|
|
142
|
+
containerId: 'email-client'
|
|
143
|
+
});
|
|
144
|
+
```
|
|
67
145
|
|
|
68
|
-
|
|
146
|
+
## Methods
|
|
69
147
|
|
|
70
|
-
|
|
148
|
+
### `loadFolders(): Promise<Folder[]>`
|
|
71
149
|
|
|
72
|
-
Load all folders/mailboxes for the account.
|
|
150
|
+
Load all folders/mailboxes for the account. Renders the folder tree when a container is set.
|
|
73
151
|
|
|
74
|
-
|
|
152
|
+
### `loadMessages(path: string, cursor?: string): Promise<MessageListResponse>`
|
|
75
153
|
|
|
76
|
-
Load messages from a
|
|
154
|
+
Load a page of messages from a folder. Pass `nextPageCursor` / `prevPageCursor` from a previous response to paginate. Resolves to `{ messages, nextPageCursor, prevPageCursor }`.
|
|
77
155
|
|
|
78
|
-
|
|
156
|
+
### `loadMessage(messageId: string): Promise<Message>`
|
|
79
157
|
|
|
80
|
-
Load a
|
|
158
|
+
Load a single message. HTML is requested with `webSafeHtml=true`, so EmailEngine returns it pre-processed with inline images embedded for safe display, and the message is marked as seen.
|
|
81
159
|
|
|
82
|
-
|
|
160
|
+
### `markAsRead(messageId: string, seen?: boolean): Promise<boolean>`
|
|
83
161
|
|
|
84
|
-
|
|
162
|
+
Add or remove the `\Seen` flag. Pass `false` to mark as unread.
|
|
85
163
|
|
|
86
|
-
|
|
164
|
+
### `deleteMessage(messageId: string): Promise<boolean>`
|
|
87
165
|
|
|
88
|
-
Delete a message.
|
|
166
|
+
Delete a message (EmailEngine moves it to Trash, or removes it if already in Trash).
|
|
89
167
|
|
|
90
|
-
|
|
168
|
+
### `moveMessage(messageId: string, targetPath: string): Promise<boolean>`
|
|
91
169
|
|
|
92
170
|
Move a message to another folder.
|
|
93
171
|
|
|
94
|
-
|
|
172
|
+
### `sendMessage(to, subject, text): Promise<object>`
|
|
95
173
|
|
|
96
|
-
Send a
|
|
174
|
+
Send a plain-text email. `to` may be:
|
|
97
175
|
|
|
98
|
-
-
|
|
99
|
-
-
|
|
100
|
-
-
|
|
176
|
+
- a string address: `'user@example.com'`
|
|
177
|
+
- an object: `{ name: 'John Doe', address: 'john@example.com' }`
|
|
178
|
+
- an array of strings and/or objects for multiple recipients
|
|
101
179
|
|
|
102
|
-
|
|
180
|
+
Resolves to EmailEngine's submit response.
|
|
103
181
|
|
|
104
|
-
|
|
182
|
+
### `downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>`
|
|
105
183
|
|
|
106
|
-
|
|
184
|
+
Browser only. Fetch an attachment and trigger a download, using the filename from the `Content-Disposition` header when available.
|
|
107
185
|
|
|
108
|
-
|
|
186
|
+
### `downloadOriginalMessage(messageId: string, subject?: string): Promise<void>`
|
|
109
187
|
|
|
110
|
-
|
|
111
|
-
- Message list with pagination
|
|
112
|
-
- Message viewer with actions (mark as read/unread, delete, move)
|
|
113
|
-
- Responsive design
|
|
114
|
-
- Dark mode support with persistent preference
|
|
188
|
+
Browser only. Download the raw message source as an `.eml` file.
|
|
115
189
|
|
|
116
|
-
|
|
117
|
-
<div id="email-client" style="height: 600px;"></div>
|
|
118
|
-
<script type="module">
|
|
119
|
-
import { EmailEngineClient } from '@postalsys/ee-client';
|
|
190
|
+
### `destroy(): void`
|
|
120
191
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
accessToken: 'your-access-token',
|
|
125
|
-
container: document.getElementById('email-client'),
|
|
126
|
-
// Optional: Custom confirm dialog
|
|
127
|
-
confirmMethod: async message => {
|
|
128
|
-
return await myCustomDialog.confirm(message);
|
|
129
|
-
}
|
|
130
|
-
});
|
|
131
|
-
</script>
|
|
132
|
-
```
|
|
192
|
+
Clean up the instance and clear the `sess_` token keep-alive interval. Always call this when you are finished with a client (for example when unmounting the UI) to avoid a leaked timer.
|
|
193
|
+
|
|
194
|
+
## Browser UI
|
|
133
195
|
|
|
134
|
-
|
|
196
|
+
When a `container` is provided the client builds a full webmail interface:
|
|
135
197
|
|
|
136
|
-
|
|
198
|
+
- Folder tree with special-folder ordering (Inbox, Drafts, Sent, Trash, Junk, Archive) and nested folders
|
|
199
|
+
- Paginated message list with a selectable page size (persisted to `localStorage`)
|
|
200
|
+
- Message viewer with mark read/unread, delete, move-to-folder, download original, and attachment downloads
|
|
201
|
+
- Compose modal (floating button) for sending plain-text mail
|
|
202
|
+
- Dark mode toggle with the preference persisted to `localStorage`
|
|
203
|
+
|
|
204
|
+
### Custom dialogs
|
|
205
|
+
|
|
206
|
+
Provide `confirmMethod` and `alertMethod` to route confirmations and alerts through your own modal system instead of the browser defaults - useful when integrating with a UI framework:
|
|
137
207
|
|
|
138
208
|
```javascript
|
|
139
209
|
const client = new EmailEngineClient({
|
|
140
|
-
apiUrl: 'https://your-emailengine-server.com',
|
|
210
|
+
apiUrl: 'https://your-emailengine-server.example.com',
|
|
141
211
|
account: 'your-account-id',
|
|
142
212
|
accessToken: 'your-access-token',
|
|
143
213
|
container: document.getElementById('email-client'),
|
|
144
214
|
|
|
145
|
-
// Custom alert method
|
|
146
215
|
alertMethod: async (message, title, cancelText, okText) => {
|
|
147
|
-
return await MyModal.alert({
|
|
148
|
-
title: title, // e.g., "Success", "Error", "Notice"
|
|
149
|
-
message: message,
|
|
150
|
-
okButton: okText // e.g., "OK"
|
|
151
|
-
// cancelText is null for alerts
|
|
152
|
-
});
|
|
216
|
+
return await MyModal.alert({ title, message, okButton: okText });
|
|
153
217
|
},
|
|
154
218
|
|
|
155
|
-
// Custom confirm method
|
|
156
219
|
confirmMethod: async (message, title, cancelText, okText) => {
|
|
157
|
-
return await MyModal.confirm({
|
|
158
|
-
title: title, // e.g., "Delete Message", "Confirm"
|
|
159
|
-
message: message,
|
|
160
|
-
cancelButton: cancelText, // e.g., "Cancel"
|
|
161
|
-
okButton: okText // e.g., "Delete", "OK"
|
|
162
|
-
});
|
|
220
|
+
return await MyModal.confirm({ title, message, cancelButton: cancelText, okButton: okText });
|
|
163
221
|
}
|
|
164
222
|
});
|
|
165
223
|
```
|
|
166
224
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
Both methods receive the same parameters:
|
|
170
|
-
|
|
171
|
-
- `message` (string): The message to display
|
|
172
|
-
- `title` (string): Dialog title (defaults: "Confirm" for confirm, "Notice" for alert)
|
|
173
|
-
- `cancelText` (string|null): Cancel button text ("Cancel" for confirm, `null` for alert)
|
|
174
|
-
- `okText` (string): OK/action button text (defaults: "OK")
|
|
225
|
+
Both methods receive the same arguments:
|
|
175
226
|
|
|
176
|
-
|
|
227
|
+
- `message` (string): text to display
|
|
228
|
+
- `title` (string): dialog title (defaults: `Confirm` / `Notice`)
|
|
229
|
+
- `cancelText` (string | null): cancel button text (`Cancel` for confirm, `null` for alert)
|
|
230
|
+
- `okText` (string): confirm/OK button text (default `OK`)
|
|
177
231
|
|
|
178
|
-
The
|
|
232
|
+
The client uses contextual titles such as `Delete Message`, `Validation Error`, `Success`, `Send Error`, and `Download Error`. `confirmMethod` should return a boolean (or a promise for one); `alertMethod` may be sync or async.
|
|
179
233
|
|
|
180
|
-
|
|
181
|
-
- **Success messages**: `alertMethod(message, "Success", null, "OK")`
|
|
182
|
-
- **Send errors**: `alertMethod(message, "Send Error", null, "OK")`
|
|
183
|
-
- **Download errors**: `alertMethod(message, "Download Error", null, "OK")`
|
|
184
|
-
- **Delete confirmation**: `confirmMethod(message, "Delete Message", "Cancel", "Delete")`
|
|
234
|
+
## Security
|
|
185
235
|
|
|
186
|
-
|
|
236
|
+
This library renders attacker-controlled email content, so it is careful about HTML injection:
|
|
187
237
|
|
|
188
|
-
|
|
238
|
+
- All untrusted values (subjects, addresses, names, filenames, folder names) are HTML-escaped before being written to the DOM.
|
|
239
|
+
- The one intentional raw-HTML sink is the message body itself. The client fetches it with EmailEngine's `webSafeHtml` option so the HTML arrives already pre-processed for safe embedding.
|
|
189
240
|
|
|
190
|
-
|
|
241
|
+
Do not disable escaping or add new raw-HTML sinks when extending the UI.
|
|
191
242
|
|
|
192
|
-
|
|
193
|
-
- **Persistent Preference**: Dark mode preference is saved to localStorage and restored on page reload
|
|
194
|
-
- **Complete Theme**: All UI components are styled for optimal readability in both light and dark modes
|
|
243
|
+
## TypeScript
|
|
195
244
|
|
|
196
|
-
|
|
245
|
+
Type declarations ship with the package (`index.d.ts`), so `EmailEngineClient`, `createEmailEngineClient`, and the exported interfaces (`Folder`, `Message`, `MessageListResponse`, `EmailEngineClientOptions`, and others) are typed out of the box - no `@types` package needed.
|
|
197
246
|
|
|
198
247
|
## License
|
|
199
248
|
|
|
200
|
-
MIT
|
|
249
|
+
MIT (c) Postal Systems OÜ
|
package/index.d.ts
CHANGED
|
@@ -26,6 +26,18 @@ export interface Folder {
|
|
|
26
26
|
status?: MessageStatus;
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
export interface FolderTreeEntry {
|
|
30
|
+
folder: Folder;
|
|
31
|
+
depth: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface Attachment {
|
|
35
|
+
id: string;
|
|
36
|
+
filename?: string;
|
|
37
|
+
contentType?: string;
|
|
38
|
+
size?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
29
41
|
export interface Message {
|
|
30
42
|
id: string;
|
|
31
43
|
subject?: string;
|
|
@@ -36,6 +48,7 @@ export interface Message {
|
|
|
36
48
|
unseen: boolean;
|
|
37
49
|
intro?: string;
|
|
38
50
|
text?: MessageText;
|
|
51
|
+
attachments?: Attachment[];
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
export interface MessageListResponse {
|
|
@@ -44,20 +57,40 @@ export interface MessageListResponse {
|
|
|
44
57
|
prevPageCursor?: string;
|
|
45
58
|
}
|
|
46
59
|
|
|
60
|
+
export type SendRecipient = string | EmailAddress;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Custom dialog handler. Invoked by the client as
|
|
64
|
+
* `(message, title, cancelText, okText)`; `cancelText` is `null` for alerts.
|
|
65
|
+
* May be synchronous or asynchronous. Confirm handlers should resolve to a boolean.
|
|
66
|
+
*/
|
|
67
|
+
export type DialogMethod = (
|
|
68
|
+
message: string,
|
|
69
|
+
title?: string,
|
|
70
|
+
cancelText?: string | null,
|
|
71
|
+
okText?: string
|
|
72
|
+
) => boolean | void | Promise<boolean | void>;
|
|
73
|
+
|
|
47
74
|
export interface EmailEngineClientOptions {
|
|
48
75
|
apiUrl?: string;
|
|
49
76
|
account: string;
|
|
50
77
|
accessToken?: string;
|
|
51
78
|
container?: HTMLElement;
|
|
52
79
|
containerId?: string;
|
|
53
|
-
|
|
80
|
+
pageSize?: number;
|
|
81
|
+
confirmMethod?: DialogMethod;
|
|
82
|
+
alertMethod?: DialogMethod;
|
|
54
83
|
}
|
|
55
84
|
|
|
56
85
|
export declare class EmailEngineClient {
|
|
57
86
|
apiUrl: string;
|
|
58
87
|
account: string;
|
|
59
88
|
accessToken?: string;
|
|
60
|
-
container?: HTMLElement;
|
|
89
|
+
container?: HTMLElement | null;
|
|
90
|
+
confirmMethod: DialogMethod;
|
|
91
|
+
alertMethod: DialogMethod;
|
|
92
|
+
pageSize: number;
|
|
93
|
+
darkMode: boolean;
|
|
61
94
|
currentFolder: string | null;
|
|
62
95
|
currentMessage: Message | null;
|
|
63
96
|
folders: Folder[];
|
|
@@ -74,17 +107,23 @@ export declare class EmailEngineClient {
|
|
|
74
107
|
markAsRead(messageId: string, seen?: boolean): Promise<boolean>;
|
|
75
108
|
deleteMessage(messageId: string): Promise<boolean>;
|
|
76
109
|
moveMessage(messageId: string, targetPath: string): Promise<boolean>;
|
|
110
|
+
sendMessage(to: SendRecipient | SendRecipient[], subject: string, text: string): Promise<any>;
|
|
111
|
+
downloadAttachment(attachmentId: string, suggestedFilename?: string): Promise<void>;
|
|
112
|
+
downloadOriginalMessage(messageId: string, subject?: string): Promise<void>;
|
|
77
113
|
formatDate(dateStr: string): string;
|
|
114
|
+
formatFileSize(bytes: number): string;
|
|
115
|
+
escapeHtml(value: unknown): string;
|
|
78
116
|
createStyles(): void;
|
|
79
|
-
|
|
80
|
-
buildFolderTree(): Folder[];
|
|
117
|
+
buildFolderTree(): FolderTreeEntry[];
|
|
81
118
|
renderFolderList(): void;
|
|
82
119
|
renderMessageList(): void;
|
|
83
120
|
renderMessage(): void;
|
|
84
121
|
createLayout(): void;
|
|
85
122
|
init(): void;
|
|
123
|
+
toggleDarkMode(): void;
|
|
124
|
+
destroy(): void;
|
|
86
125
|
}
|
|
87
126
|
|
|
88
|
-
export declare function createEmailEngineClient(options: EmailEngineClientOptions
|
|
127
|
+
export declare function createEmailEngineClient(options: EmailEngineClientOptions): EmailEngineClient;
|
|
89
128
|
|
|
90
|
-
export default EmailEngineClient;
|
|
129
|
+
export default EmailEngineClient;
|
package/index.js
CHANGED
|
@@ -3,7 +3,20 @@ export class EmailEngineClient {
|
|
|
3
3
|
this.apiUrl = options.apiUrl || 'http://127.0.0.1:3000';
|
|
4
4
|
this.account = options.account;
|
|
5
5
|
this.accessToken = options.accessToken;
|
|
6
|
-
this.container = options.container;
|
|
6
|
+
this.container = options.container || null;
|
|
7
|
+
// Resolve containerId when no element was passed directly, so
|
|
8
|
+
// `new EmailEngineClient({ containerId })` renders UI too (not only the
|
|
9
|
+
// factory). In a non-DOM env this stays null - an API-only client.
|
|
10
|
+
if (!this.container && options.containerId && typeof document !== 'undefined') {
|
|
11
|
+
this.container = document.getElementById(options.containerId);
|
|
12
|
+
// A containerId that matches nothing is almost always a typo; warn
|
|
13
|
+
// rather than silently degrading to a UI-less, API-only client.
|
|
14
|
+
if (!this.container) {
|
|
15
|
+
console.warn(
|
|
16
|
+
`EmailEngineClient: no element found for containerId "${options.containerId}"; UI rendering disabled`
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
7
20
|
this.confirmMethod =
|
|
8
21
|
options.confirmMethod ||
|
|
9
22
|
((message, _title = 'Confirm', _cancelText = 'Cancel', _okText = 'OK') => confirm(message));
|
|
@@ -17,6 +30,11 @@ export class EmailEngineClient {
|
|
|
17
30
|
this.nextPageCursor = null;
|
|
18
31
|
this.prevPageCursor = null;
|
|
19
32
|
|
|
33
|
+
// Set once destroy() runs; guards async completions (loadFolders,
|
|
34
|
+
// loadMessages, loadMessage) from re-rendering or scrolling into a
|
|
35
|
+
// torn-down - or recreated - container.
|
|
36
|
+
this._destroyed = false;
|
|
37
|
+
|
|
20
38
|
// Keep-alive timer for sess_ tokens
|
|
21
39
|
this.keepAliveTimer = null;
|
|
22
40
|
this.lastActivity = Date.now();
|
|
@@ -30,7 +48,8 @@ export class EmailEngineClient {
|
|
|
30
48
|
// Get page size from localStorage or options or default
|
|
31
49
|
const savedPageSize =
|
|
32
50
|
typeof window !== 'undefined' && window.localStorage ? localStorage.getItem('ee-client-page-size') : null;
|
|
33
|
-
|
|
51
|
+
const requestedPageSize = savedPageSize ? parseInt(savedPageSize, 10) : parseInt(options.pageSize, 10);
|
|
52
|
+
this.pageSize = requestedPageSize > 0 ? requestedPageSize : 20;
|
|
34
53
|
|
|
35
54
|
if (this.container) {
|
|
36
55
|
this.init();
|
|
@@ -48,32 +67,32 @@ export class EmailEngineClient {
|
|
|
48
67
|
const options = {
|
|
49
68
|
method: method,
|
|
50
69
|
headers: {
|
|
51
|
-
'Content-Type': 'application/json'
|
|
70
|
+
'Content-Type': 'application/json',
|
|
71
|
+
...this._authHeaders()
|
|
52
72
|
}
|
|
53
73
|
};
|
|
54
74
|
|
|
55
|
-
if (this.accessToken) {
|
|
56
|
-
options.headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
75
|
if (data) {
|
|
60
76
|
options.body = JSON.stringify(data);
|
|
61
77
|
}
|
|
62
78
|
|
|
63
79
|
let fetchFn = globalThis.fetch;
|
|
64
|
-
if (!fetchFn
|
|
80
|
+
if (!fetchFn) {
|
|
81
|
+
// Native fetch is missing (older Node.js). Fall back to node-fetch.
|
|
82
|
+
// This is a dynamic import so browsers and modern Node never load it.
|
|
65
83
|
try {
|
|
66
84
|
const nodeFetch = await import('node-fetch');
|
|
67
85
|
fetchFn = nodeFetch.default;
|
|
68
86
|
} catch (err) {
|
|
69
|
-
|
|
70
|
-
'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
|
|
71
|
-
);
|
|
87
|
+
// node-fetch is not installed; the guard below reports it
|
|
72
88
|
}
|
|
73
89
|
}
|
|
74
90
|
|
|
75
91
|
if (!fetchFn) {
|
|
76
|
-
|
|
92
|
+
// Either node-fetch is missing or it exposed no callable default export
|
|
93
|
+
throw new Error(
|
|
94
|
+
'fetch is not available. In Node.js environments, please install node-fetch: npm install node-fetch'
|
|
95
|
+
);
|
|
77
96
|
}
|
|
78
97
|
|
|
79
98
|
const response = await fetchFn(url, options);
|
|
@@ -99,6 +118,7 @@ export class EmailEngineClient {
|
|
|
99
118
|
try {
|
|
100
119
|
const data = await this.apiRequest('GET', `/v1/account/${this.account}/mailboxes`);
|
|
101
120
|
this.folders = data.mailboxes || [];
|
|
121
|
+
this._folderTreeCache = null;
|
|
102
122
|
if (this.container) {
|
|
103
123
|
this.renderFolderList();
|
|
104
124
|
}
|
|
@@ -181,7 +201,7 @@ export class EmailEngineClient {
|
|
|
181
201
|
}
|
|
182
202
|
}
|
|
183
203
|
|
|
184
|
-
if (this.container) {
|
|
204
|
+
if (this.container && !this._destroyed) {
|
|
185
205
|
this.renderMessage();
|
|
186
206
|
|
|
187
207
|
// Scroll to top of the email client container
|
|
@@ -321,23 +341,18 @@ export class EmailEngineClient {
|
|
|
321
341
|
_formatSendError(error) {
|
|
322
342
|
// If we have detailed error information from the API
|
|
323
343
|
if (error.details && error.details.fields && Array.isArray(error.details.fields)) {
|
|
324
|
-
const fieldErrors = error.details.fields
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
//
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
message = message.replace('"text"', 'message');
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
return message;
|
|
340
|
-
});
|
|
344
|
+
const fieldErrors = error.details.fields
|
|
345
|
+
// Keep only entries that carry a usable message string.
|
|
346
|
+
.filter(field => field && typeof field.message === 'string')
|
|
347
|
+
// Map technical field names to user-friendly ones. Each replace
|
|
348
|
+
// is a no-op when its pattern is absent, so no includes-guards
|
|
349
|
+
// are needed - and to[N] for any index is handled, not just to[0].
|
|
350
|
+
.map(field =>
|
|
351
|
+
field.message
|
|
352
|
+
.replace(/to\[\d+\]\.address|"address"/g, 'email address')
|
|
353
|
+
.replace(/"subject"/g, 'subject')
|
|
354
|
+
.replace(/"text"/g, 'message')
|
|
355
|
+
);
|
|
341
356
|
|
|
342
357
|
const mainMessage = error.details.message || 'Failed to send email';
|
|
343
358
|
if (fieldErrors.length > 0) {
|
|
@@ -381,21 +396,43 @@ export class EmailEngineClient {
|
|
|
381
396
|
return String(value).replace(/[&<>"']/g, ch => htmlEscapes[ch]);
|
|
382
397
|
}
|
|
383
398
|
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
399
|
+
_authHeaders() {
|
|
400
|
+
const headers = {};
|
|
401
|
+
if (this.accessToken) {
|
|
402
|
+
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
403
|
+
}
|
|
404
|
+
return headers;
|
|
405
|
+
}
|
|
390
406
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
407
|
+
_saveBlob(blob, filename) {
|
|
408
|
+
const url = window.URL.createObjectURL(blob);
|
|
409
|
+
const a = document.createElement('a');
|
|
410
|
+
a.href = url;
|
|
411
|
+
a.download = filename;
|
|
412
|
+
document.body.appendChild(a);
|
|
413
|
+
a.click();
|
|
414
|
+
document.body.removeChild(a);
|
|
415
|
+
window.URL.revokeObjectURL(url);
|
|
416
|
+
}
|
|
395
417
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
418
|
+
// Authenticated GET for binary payloads (attachments, message source).
|
|
419
|
+
// apiRequest is not reused here - it always parses the body as JSON.
|
|
420
|
+
async _fetchBlob(endpoint) {
|
|
421
|
+
const response = await fetch(`${this.apiUrl}${endpoint}`, {
|
|
422
|
+
headers: this._authHeaders(),
|
|
423
|
+
credentials: 'include'
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
if (!response.ok) {
|
|
427
|
+
throw new Error(`HTTP error! status: ${response.status}`);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
return response;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async downloadAttachment(attachmentId, suggestedFilename = null) {
|
|
434
|
+
try {
|
|
435
|
+
const response = await this._fetchBlob(`/v1/account/${this.account}/attachment/${attachmentId}`);
|
|
399
436
|
|
|
400
437
|
// Get filename from Content-Disposition header if available
|
|
401
438
|
const contentDisposition = response.headers.get('content-disposition');
|
|
@@ -407,18 +444,9 @@ export class EmailEngineClient {
|
|
|
407
444
|
}
|
|
408
445
|
}
|
|
409
446
|
|
|
410
|
-
// Get the attachment data
|
|
447
|
+
// Get the attachment data and trigger the download
|
|
411
448
|
const blob = await response.blob();
|
|
412
|
-
|
|
413
|
-
// Create a download link
|
|
414
|
-
const url = window.URL.createObjectURL(blob);
|
|
415
|
-
const a = document.createElement('a');
|
|
416
|
-
a.href = url;
|
|
417
|
-
a.download = filename;
|
|
418
|
-
document.body.appendChild(a);
|
|
419
|
-
a.click();
|
|
420
|
-
document.body.removeChild(a);
|
|
421
|
-
window.URL.revokeObjectURL(url);
|
|
449
|
+
this._saveBlob(blob, filename);
|
|
422
450
|
} catch (error) {
|
|
423
451
|
console.error('Failed to download attachment:', error);
|
|
424
452
|
this.alertMethod('Failed to download attachment. Please try again.', 'Download Error', null, 'OK');
|
|
@@ -427,19 +455,7 @@ export class EmailEngineClient {
|
|
|
427
455
|
|
|
428
456
|
async downloadOriginalMessage(messageId, subject = null) {
|
|
429
457
|
try {
|
|
430
|
-
const
|
|
431
|
-
if (this.accessToken) {
|
|
432
|
-
headers['Authorization'] = `Bearer ${this.accessToken}`;
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
const response = await fetch(`${this.apiUrl}/v1/account/${this.account}/message/${messageId}/source`, {
|
|
436
|
-
headers,
|
|
437
|
-
credentials: 'include'
|
|
438
|
-
});
|
|
439
|
-
|
|
440
|
-
if (!response.ok) {
|
|
441
|
-
throw new Error(`HTTP error! status: ${response.status}`);
|
|
442
|
-
}
|
|
458
|
+
const response = await this._fetchBlob(`/v1/account/${this.account}/message/${messageId}/source`);
|
|
443
459
|
|
|
444
460
|
// Get the email data
|
|
445
461
|
const blob = await response.blob();
|
|
@@ -450,15 +466,7 @@ export class EmailEngineClient {
|
|
|
450
466
|
const safeSubject = subject ? subject.replace(/[^a-z0-9]/gi, '_').substring(0, 50) : 'email';
|
|
451
467
|
const filename = `${dateStr}_${safeSubject}.eml`;
|
|
452
468
|
|
|
453
|
-
|
|
454
|
-
const url = window.URL.createObjectURL(blob);
|
|
455
|
-
const a = document.createElement('a');
|
|
456
|
-
a.href = url;
|
|
457
|
-
a.download = filename;
|
|
458
|
-
document.body.appendChild(a);
|
|
459
|
-
a.click();
|
|
460
|
-
document.body.removeChild(a);
|
|
461
|
-
window.URL.revokeObjectURL(url);
|
|
469
|
+
this._saveBlob(blob, filename);
|
|
462
470
|
} catch (error) {
|
|
463
471
|
console.error('Failed to download original message:', error);
|
|
464
472
|
this.alertMethod('Failed to download original message. Please try again.', 'Download Error', null, 'OK');
|
|
@@ -1273,18 +1281,14 @@ export class EmailEngineClient {
|
|
|
1273
1281
|
}
|
|
1274
1282
|
`;
|
|
1275
1283
|
document.head.appendChild(style);
|
|
1284
|
+
this._styleElement = style;
|
|
1276
1285
|
}
|
|
1277
1286
|
|
|
1278
|
-
|
|
1279
|
-
if (
|
|
1280
|
-
return
|
|
1287
|
+
buildFolderTree() {
|
|
1288
|
+
if (this._folderTreeCache) {
|
|
1289
|
+
return this._folderTreeCache;
|
|
1281
1290
|
}
|
|
1282
1291
|
|
|
1283
|
-
const pathParts = folder.path.split(folder.delimiter);
|
|
1284
|
-
return Math.max(0, pathParts.length - 1);
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
buildFolderTree() {
|
|
1288
1292
|
const specialFolders = [];
|
|
1289
1293
|
const regularFolders = [];
|
|
1290
1294
|
|
|
@@ -1319,34 +1323,52 @@ export class EmailEngineClient {
|
|
|
1319
1323
|
return a.name.localeCompare(b.name);
|
|
1320
1324
|
});
|
|
1321
1325
|
|
|
1322
|
-
|
|
1323
|
-
|
|
1326
|
+
// Index children by parent in a single pass so the hierarchy walk is
|
|
1327
|
+
// O(n) instead of re-filtering the whole list at every level. A folder
|
|
1328
|
+
// whose parent is not among the regular folders (special-use parent,
|
|
1329
|
+
// missing parent, or no parent) is a root, keyed under null - those must
|
|
1330
|
+
// still surface at the top level rather than be dropped.
|
|
1331
|
+
const regularPaths = new Set(regularFolders.map(f => f.path));
|
|
1332
|
+
const childrenByParent = new Map();
|
|
1333
|
+
regularFolders.forEach(folder => {
|
|
1334
|
+
const key = regularPaths.has(folder.parentPath) ? folder.parentPath : null;
|
|
1335
|
+
const siblings = childrenByParent.get(key);
|
|
1336
|
+
if (siblings) {
|
|
1337
|
+
siblings.push(folder);
|
|
1338
|
+
} else {
|
|
1339
|
+
childrenByParent.set(key, [folder]);
|
|
1340
|
+
}
|
|
1341
|
+
});
|
|
1342
|
+
childrenByParent.forEach(siblings => siblings.sort((a, b) => a.name.localeCompare(b.name)));
|
|
1324
1343
|
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1344
|
+
// Each entry carries its depth in the rendered tree (roots = 0). Depth
|
|
1345
|
+
// comes from tree position, not the path string, so a folder whose
|
|
1346
|
+
// parent is a special-use or missing folder renders flush at the top.
|
|
1347
|
+
const visited = new Set();
|
|
1348
|
+
const walk = (parentKey, depth) => {
|
|
1349
|
+
const result = [];
|
|
1350
|
+
const siblings = childrenByParent.get(parentKey) || [];
|
|
1351
|
+
siblings.forEach(folder => {
|
|
1352
|
+
// Guard against cyclic/self-referential parentPath values.
|
|
1353
|
+
if (visited.has(folder.path)) {
|
|
1354
|
+
return;
|
|
1330
1355
|
}
|
|
1356
|
+
visited.add(folder.path);
|
|
1357
|
+
result.push({ folder, depth });
|
|
1358
|
+
result.push(...walk(folder.path, depth + 1));
|
|
1331
1359
|
});
|
|
1332
|
-
|
|
1333
|
-
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
1334
|
-
|
|
1335
|
-
children.forEach(folder => {
|
|
1336
|
-
result.push(folder);
|
|
1337
|
-
result.push(...buildHierarchy(folders, folder.path, depth + 1));
|
|
1338
|
-
});
|
|
1339
|
-
|
|
1340
1360
|
return result;
|
|
1341
1361
|
};
|
|
1342
1362
|
|
|
1343
|
-
const hierarchicalRegular =
|
|
1363
|
+
const hierarchicalRegular = walk(null, 0);
|
|
1344
1364
|
|
|
1345
|
-
|
|
1365
|
+
const tree = [...specialFolders.map(folder => ({ folder, depth: 0 })), ...hierarchicalRegular];
|
|
1366
|
+
this._folderTreeCache = tree;
|
|
1367
|
+
return tree;
|
|
1346
1368
|
}
|
|
1347
1369
|
|
|
1348
1370
|
renderFolderList() {
|
|
1349
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1371
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1350
1372
|
return;
|
|
1351
1373
|
}
|
|
1352
1374
|
|
|
@@ -1356,13 +1378,15 @@ export class EmailEngineClient {
|
|
|
1356
1378
|
}
|
|
1357
1379
|
|
|
1358
1380
|
const sortedFolders = this.buildFolderTree();
|
|
1381
|
+
// Precompute which paths are some folder's parent so the per-row
|
|
1382
|
+
// has-children check is O(1) instead of scanning this.folders each time.
|
|
1383
|
+
const parentPaths = new Set(this.folders.map(f => f.parentPath));
|
|
1359
1384
|
|
|
1360
1385
|
const html = `
|
|
1361
1386
|
<ul class="ee-folder-list">
|
|
1362
1387
|
${sortedFolders
|
|
1363
|
-
.map(folder => {
|
|
1364
|
-
const
|
|
1365
|
-
const hasChildren = this.folders.some(f => f.parentPath === folder.path);
|
|
1388
|
+
.map(({ folder, depth }) => {
|
|
1389
|
+
const hasChildren = parentPaths.has(folder.path);
|
|
1366
1390
|
return `
|
|
1367
1391
|
<li class="ee-folder-item ${folder.path === this.currentFolder ? 'active' : ''}"
|
|
1368
1392
|
data-path="${this.escapeHtml(folder.path)}"
|
|
@@ -1389,7 +1413,7 @@ export class EmailEngineClient {
|
|
|
1389
1413
|
}
|
|
1390
1414
|
|
|
1391
1415
|
renderMessageList() {
|
|
1392
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1416
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1393
1417
|
return;
|
|
1394
1418
|
}
|
|
1395
1419
|
|
|
@@ -1489,7 +1513,7 @@ export class EmailEngineClient {
|
|
|
1489
1513
|
}
|
|
1490
1514
|
|
|
1491
1515
|
renderMessage() {
|
|
1492
|
-
if (typeof document === 'undefined' || !this.container) {
|
|
1516
|
+
if (typeof document === 'undefined' || !this.container || this._destroyed) {
|
|
1493
1517
|
return;
|
|
1494
1518
|
}
|
|
1495
1519
|
|
|
@@ -1513,8 +1537,7 @@ export class EmailEngineClient {
|
|
|
1513
1537
|
<select class="ee-button" data-action="move">
|
|
1514
1538
|
<option value="">Move to...</option>
|
|
1515
1539
|
${this.buildFolderTree()
|
|
1516
|
-
.map(folder => {
|
|
1517
|
-
const depth = this.calculateFolderDepth(folder);
|
|
1540
|
+
.map(({ folder, depth }) => {
|
|
1518
1541
|
const indent = ' '.repeat(depth);
|
|
1519
1542
|
const prefix = depth > 0 ? '└ ' : '';
|
|
1520
1543
|
return `<option value="${this.escapeHtml(folder.path)}" ${folder.path === this.currentFolder ? 'disabled' : ''}>${indent}${prefix}${this.escapeHtml(folder.name)}</option>`;
|
|
@@ -1721,11 +1744,12 @@ export class EmailEngineClient {
|
|
|
1721
1744
|
});
|
|
1722
1745
|
|
|
1723
1746
|
// Close on Escape key
|
|
1724
|
-
|
|
1747
|
+
this._composeKeydownHandler = e => {
|
|
1725
1748
|
if (e.key === 'Escape' && modal.classList.contains('show')) {
|
|
1726
1749
|
closeModal();
|
|
1727
1750
|
}
|
|
1728
|
-
}
|
|
1751
|
+
};
|
|
1752
|
+
document.addEventListener('keydown', this._composeKeydownHandler);
|
|
1729
1753
|
|
|
1730
1754
|
// Send email
|
|
1731
1755
|
sendButton.addEventListener('click', async () => {
|
|
@@ -1928,6 +1952,11 @@ export class EmailEngineClient {
|
|
|
1928
1952
|
localStorage.setItem('ee-client-dark-mode', this.darkMode.toString());
|
|
1929
1953
|
}
|
|
1930
1954
|
|
|
1955
|
+
// DOM updates only apply to the rendered UI; skip without a container
|
|
1956
|
+
if (!this.container) {
|
|
1957
|
+
return;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1931
1960
|
// Update UI
|
|
1932
1961
|
const client = this.container.querySelector('.ee-client');
|
|
1933
1962
|
if (client) {
|
|
@@ -1946,40 +1975,61 @@ export class EmailEngineClient {
|
|
|
1946
1975
|
}
|
|
1947
1976
|
|
|
1948
1977
|
destroy() {
|
|
1978
|
+
// Mark destroyed first so any in-flight async completion skips
|
|
1979
|
+
// re-rendering into a torn-down or recreated container.
|
|
1980
|
+
this._destroyed = true;
|
|
1981
|
+
|
|
1949
1982
|
// Clean up keep-alive timer
|
|
1950
1983
|
if (this.keepAliveTimer) {
|
|
1951
1984
|
clearInterval(this.keepAliveTimer);
|
|
1952
1985
|
this.keepAliveTimer = null;
|
|
1953
1986
|
}
|
|
1987
|
+
|
|
1988
|
+
// Remove the compose button's window scroll/resize listeners
|
|
1989
|
+
if (this._composeButtonCleanup) {
|
|
1990
|
+
this._composeButtonCleanup();
|
|
1991
|
+
this._composeButtonCleanup = null;
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
// Remove the document-level Escape keydown listener
|
|
1995
|
+
if (this._composeKeydownHandler && typeof document !== 'undefined') {
|
|
1996
|
+
document.removeEventListener('keydown', this._composeKeydownHandler);
|
|
1997
|
+
this._composeKeydownHandler = null;
|
|
1998
|
+
}
|
|
1999
|
+
|
|
2000
|
+
// Remove the injected stylesheet
|
|
2001
|
+
if (this._styleElement && this._styleElement.parentNode) {
|
|
2002
|
+
this._styleElement.parentNode.removeChild(this._styleElement);
|
|
2003
|
+
this._styleElement = null;
|
|
2004
|
+
}
|
|
1954
2005
|
}
|
|
1955
2006
|
}
|
|
1956
2007
|
|
|
1957
2008
|
export function createEmailEngineClient(options) {
|
|
1958
|
-
if (typeof options
|
|
1959
|
-
options
|
|
1960
|
-
container: typeof document !== 'undefined' ? document.getElementById(options) : null
|
|
1961
|
-
};
|
|
1962
|
-
} else if (typeof HTMLElement !== 'undefined' && options instanceof HTMLElement) {
|
|
1963
|
-
options = {
|
|
1964
|
-
container: options
|
|
1965
|
-
};
|
|
1966
|
-
} else if (typeof options === 'object' && options.containerId) {
|
|
1967
|
-
options.container = typeof document !== 'undefined' ? document.getElementById(options.containerId) : null;
|
|
2009
|
+
if (!options || typeof options !== 'object') {
|
|
2010
|
+
throw new Error('Invalid options: expected an options object');
|
|
1968
2011
|
}
|
|
1969
2012
|
|
|
1970
|
-
if (
|
|
1971
|
-
throw new Error('
|
|
2013
|
+
if (!options.account) {
|
|
2014
|
+
throw new Error('Account identifier is required');
|
|
1972
2015
|
}
|
|
1973
2016
|
|
|
1974
2017
|
if (!options.apiUrl) {
|
|
1975
2018
|
console.warn('No API URL specified, using default http://127.0.0.1:3000');
|
|
1976
2019
|
}
|
|
1977
2020
|
|
|
1978
|
-
|
|
1979
|
-
|
|
2021
|
+
const client = new EmailEngineClient(options);
|
|
2022
|
+
|
|
2023
|
+
// The constructor is the single place that resolves containerId to an
|
|
2024
|
+
// element. In a DOM environment a containerId that matches nothing is a
|
|
2025
|
+
// caller error, so fail loudly here - and tear down the half-built client
|
|
2026
|
+
// so its keep-alive timer does not leak.
|
|
2027
|
+
if (options.containerId && !client.container && typeof document !== 'undefined') {
|
|
2028
|
+
client.destroy();
|
|
2029
|
+
throw new Error('Container element not found');
|
|
1980
2030
|
}
|
|
1981
2031
|
|
|
1982
|
-
return
|
|
2032
|
+
return client;
|
|
1983
2033
|
}
|
|
1984
2034
|
|
|
1985
2035
|
export default EmailEngineClient;
|